Express server using npm in node.JS and handling routes.

Onkar Shingate
Geek Culture
Published in
3 min readMay 24, 2021

1) How to create a basic server using express in node.JS

  • first, we have to create a package.json file into our project by using the following command:- “npm init
  • after creating the package.json file we have to install express using npm and have to make its entry into the package.json file by using the command as following: “ npm install express - -save ”.
  • now we just have to import the express module by requiring it. after that, we have to create a new variable and store the value returned by express().see in the image below:-
creating basic server
  • once the steps above are done, then we have to call listen to a method which accepts 1st parameter as the port on which server is to be deployed. and call back function as a second optional parameter

— — In this way the basic server is created using Express in node.js

2) Handle routes in Express.

  • Suppose we have to handle “ GET ” method on route “ / ”(index route).
  • we can use methods in app variable to handle route as below:-
express handle GET method on route “ / ”
  • as shown above we have to use app.[method_name] () method to handle any method we want.
  • as in the above example, it accepts 2 parameters:

1) Route.

2) call back function.

  • call back function accepts two parameters “request” and “response”.
  • we can use “res.send()” or “res.sendFile()” methods inside call back function to end the response.

Note:- res.sendFile() accepts only absolute path of the file.

3) How to handle CSS files and image routes in Express.

  • to handle CSS files and images in the project we have to use express.static() method.
  • express offers us a very simple way to handle CSS files and image Requests and we don't need to create a separate route for everything.
  • First, we have to move all our assets into one folder suppose “ public ” folder.
  • Now to check the request method and request URL of the coming request we can use middleware to Console.log() on every route as shown in the below image.
static method to handle images and CSS files.
  • now we can use express.static() method inside middleware which accepts the only absolute path of the public folder.
  • Now we are done .now we don't have to handle routes for images and CSS files.

5) Access the data Coming from the body of the URL.

  • we can use middleware to fetch body data of URL.
  • express offers“ express.json() ” and “express.urlencoded()” method .
  • express.json() :- this method is used when the incoming data is in JSON format.
  • express.urlencoded() :- this method is used when data is in URL string format.
  • after that, we can access that data while handling routes using the req object “ req.body ”.
  • refer image below:-
fetching data from req.body.

--

--