Node Js - Handle client requests with Express Routing
Routing in Express
Routing simply means to configure endpoints in your node application so that it can handle various client requests (Get, Post, etc).
Each route must have a callback function (or handler functions) configured in your code. A Route can have one or more than one handlers configured and the handler will be executed when the Route is matched with the client request URL and method (Get, POST).
Route definition has the following structure:
expressServer.METHOD(Path, Handler)
For example:
below is the example of a GET request to the homepage(root) of your app.
expressServer.get('/',(req,res)=>{
res.send('<b>Home Page...</b>')
})
below is the example of a GET request to the /about page of your app
expressServer.get('/about',(req,res) =>{
res.send('<h2>We are at About Page</h2>')
})
First Parameter (/about) is the path that the Route is handling.
Second Parameter is the handler function.
Note: We are using arrow function as a handler, This is a shorthand syntax of a function that takes two parameters i.e req, res.
Code for your Reference:
const express = require("express");
const expressServer = express();
expressServer.get("", (req, res) => {
res.send('Hello Express...')
});
expressServer.listen(8000, ()=>{
console.log('Node is up and running on 8000')
})
expressServer.get('/users',(req,res)=>{
res.send('<b>List of Users...</b>')
})
expressServer.get('/about',(req,res) =>{
res.send('<h2>We are at About Page</h2>')
})
In the above example, we returned a very basic Html to the get request.
The same way you can handle POST, PUT, DELETE, PATCH and other Http methods using the Routers in the express.
expressServer.post('/',(req,res) =>{
res.send('Post request to the app')
})
Handle a request using a multiple callbacks
expressServer.get('/products/book', (req, res, next)=>{
console.log('The response will be send by next function')
next()
},(req,res)=>{
res.send('Books...')
})
Chain multiple route handlers using route()
You can chain multiple route handlers by using expressServer.route().
expressServer.route('/product')
.get(function (req, res) {
res.send('Get a product')
})
.post(function (req, res) {
res.send('Add a product')
})
.put(function (req, res) {
res.send('Update the product')
})
0 Comments