Basics of Routing In Express

Basics of Routing In Express

Basic Routing

Routing in the context of creating API(Application Programing Interface) simply means how an application from the backend (server) responds to the requests from the frontend(client).

Router is basically a piece of software that redirects the user to the particular resource for a particular request method

Routing Using Express

  • Express is a NodeJS framework use to build backend APIs and web applications.

  • To use Express in your application first install it using the command npm install express in your terminal

  • Okay How to send the request to the backend for that some methods or ways should be there right?

yes, your right there are methods and rules around that those are called as HTTP request methods and these methods are also called as HTTP request verbs. There are a lot of methods but most commonly used are four methods those are GET,POST,PUT,DELETE you can refer here for more info HTTP Request Methods

  • require or import express inside your file in my case I called it as app.js and create a instance of express and assign it to app as shown in below code snippet
const express=require('express');
const app=express();
  • To listen on a particular port assign the port number to port variable like so const port=3000

  • And we need to use listen method to listen on that port and a callback function to send back some response

app.listen(port,() => {
   console.log(`server started on http://localhost:${port}`)
})
  • So to get some response from the server running on the localhost we have to use GET HTTP request method In this case I am using root route "/" you can also use something like /home to see the response. So here the call back function takes two arguments called as request(req) and response(res)

    app.get("/",(req,res) => {
         res.send("home page");
    })
    
  • To put everything together it looks like below.

const express=require('express');
const app=express();
const port=3000;
app.get("/",(req,res) => {
    res.send("home page");
})
app.listen(port,() => {
    console.log(`server started on http://localhost:${port}`);
})

Run the above code by giving the command node app.js in the terminal

To see the result open the link http://localhost:3000

  • In the above request we used GET request method that can be generalized as below.

app.METHOD(PATH,HANDLER)

where,

  • app is an instance of express

  • METHOD is an HTTP request method

  • PATH is a path on the server

  • HANDLER is a function executed when the route is matched

Example Requests

//To GET
app.get("/",(res,req)=>{res.send("home route")})
// To POST
app.post("/",(res.req) => {res.send("post request")})
//Respond To PUT  request on the `/user` route
app.put("/user",(res,req) => {res.send("put request")})
//Respond DELETE request on the `/user` route
app.delete("/user",(res,req) => {res.send("delete request")})
  • We can use app.all() method to handle all the HTTP methods.

  • We can use app.use() to specify middleware as the callback function

  • As we saw above routing methods have callback function also called as handler functions and they are called when application request to the specified route(endpoint) and HTTP method.

  • Routing methods can have more than one callback function as arguments. With multiple callback functions we need to provide next() as an argument to the callback function and then call next() within the body of the function to handoff control to next callback.

  • As I already said there is a method called as app.all() it is used to load middleware functions at a path for all HTTP methods. The below handler is executed for requests to route /dashboard whether we are using GET,PUT,POST,DELETE or any other HTTP method.

app.all('/dashboard',(req,res,next) => {
      console.log("welcome to dashboard")
      next()
})

Route Parameters in Express

  • Route parameters are basically variables derived from the named section of the URL. The captured values are stored in req.params as object.See the below example

Route path: /users/:userId/books/:bookId

Request URL: localhost:3000/users/34/books/8989

req.params: { "userId": "34", "bookId": "8989" }

  • To define the routes with route parameters we need to specify route parameters in the path of the route as shown below.
app.get('/users/:userId/books/:bookId',(req,res) => {
    res.status(200).json(req.params)
})

If we test this inside the browser we get below output ![route-params](

image.png