DEV Community

loading...

Build your first ExpressJs server from scratch.

rizkyrajitha profile image Rajitha Gunathilake ・4 min read

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 .

Alt Text

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.

Alt Text

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

  1. express - to spin up our expressjs server
  2. body-parser - a middleware to parse the body of incomming requests
  3. 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

Alt Text

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

Alt Text

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.

Alt Text

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

Alt Text

we can also see morgan logging some useful information in the console.

Alt Text

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

Alt Text

we will get and error message. that's because we didn't specify that path.

Alt Text

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.

Alt Text


final app.js

Thank you for reading until the end. If you have any unclear part feel free to drop a comment and I'll try my best to help you out. and if you have suggestions please let me know in the comment section.

Cheers 🥂 , Have a Nice Day.

Discussion (3)

pic
Editor guide
Collapse
creativesuraj profile image
Suraj Sharma

Good read!

Collapse
rizkyrajitha profile image
Collapse
superprogrammernavi profile image
Navi Dhillon

Thank you so much! This really helped me set up my first Express server <3