Hi everyone ,
In this article , i will show you how to spin up an Expressjs server using NodeJS. This tutorial will be pretty basic , and ideal for a beginner.
So Let's get started.
make a new directory and go to that directory
if you are using VScode you can open a directory , from CMD using code .
then run npm init
to initialize a project.
if you are lazy like me you can run
npm init -y
to initialize a project with default settings.
this will create a package.json
file with the information you provide.
this file is an essential component for a npm project, since we specify many details about the project such as dependencies,scripts,licence etc. by looking at a package.json
file you can get a rough idea about what is it. Enough with the package.json
file.let's move on.
Now we successfully created a project , next thing is to install the dependencies.we need few dependencies to start making our server
- express - to spin up our expressjs server
-
body-parser - a
middleware
to parse the body of incomming requests -
morgan - a
middleware
utility tool that logs the server events (this is not essential but useful for debugging)
to install these dependencies run npm i express body-parser morgan
and also i highly recommend you to install nodemon . nodemon
is also a utility tool that allows you to restart your server after changing the code , so you don't need to manually restart.
to install nodemon
run npm i -g nodemon
now all the dependencies are installed and ready to go.
Next, we are going to create our first and only file. all mighty app.js
in the app.js file first, we will import the dependencies we installed.
const express = require('express')
const bp = require("body-parser")
then we will decide a port number where your server listens.
it's better to choose a port number higher than 1024 because there are privileged ports and they might require special access.
so let's stay in a safe zone.
const port = 5000
next, we need to make an express app we can work with to that
const app = express()
app.use() is a function that we use to attach middlewares to an express application.here what we are doing is attaching the middlewares for
body-parser
, and morgan
.it allows us to use their functionalities.
app.use(bp.urlencoded({ extended: false }))
app.use(bp.json())
app.use(require("morgan")("dev"))
Ok then now we have configured or app lets wire up our first route.
I'll start with a simple hello world get
route.
app.get("/", (req, res) => { res.send("hello world"); });
after specifying a route, we have to tell where should your app listen to. we only declare the variable with port, now we have to specify that port for listening.
app.listen(port, () => { console.log("Express server listning on port " + port); });
and after this, what left is to run our server. I will use nodemon to run the server.
nodemon app.js
if you didn't install nodemon
, you can still run your app by
node app.js
if you did everything correctly, you can see Express server listening on port 5000 messages in your console.
now visit http://localhost:5000/
with your browser. you can see you hello world text in the browser.
if you used a different port use that specific port
we can also see morgan
logging some useful information in the console.
let's dig deeper into app.get()
function, we used it but we don't know how it works.
we used app.get()
make a new get request route. you can make PUT POST DELETE
requests upon your requirement.
POST
and GET
are the most common types of Http requests.
so here we used app.get()
because we wanted a get request.
if you want to go with post request use app.post()
app.get()
function first parameter we have to pass is our preferred path
. this path
is the string that specifies which route should it hit in the server.
for example if you used helloworld
app.get("/helloworld", (req, res) => { res.send("hello world"); });
we can access it using http://localhost:5000/helloworld
we will get and error message. that's because we didn't specify that path.
next is a callback function with two objects req
, res
.
req
object has all the information about the request like
headers request body etc.
res
object well handle how you respond to that request.
res.send()
method will send a plain text to that request as a response.
we also have res.json()
which we can use to send JSON data.
app.get("/", (req, res) => { var obj = { name: "rizky" }; res.json(obj); });
you can see we got a JSON response.
final app.js
Top comments (3)
Good read!
Thank you sir
Thank you so much! This really helped me set up my first Express server <3