May 21, 2024

ExpressJS Routing With Examples

With routing you can determine how your web application responds to a client request coming through a particular endpoint (path) and a specific HTTP request method (GET, POST, PUT and so on). In this post we'll see how to set up basic routing in ExpressJS.

Routing in Express

Using the object, conventionally named 'app', you get from the express() function you get access to the methods that corresponds to the HTTP methods.

Format for calling methods is as given below

app.METHOD(path, callback [, callback ...])

where METHOD is the HTTP method of the request, such as GET, PUT, POST, and so on, in lowercase.

  • app.get() to handle GET requests (fetching resource)
  • app.post() to handle POST requests (adding new resource)
  • app.put() to handle PUT requests (updating resource)
  • app.delete() to handle DELETE requests (deleting resource)

Thus the methods you'll actually call are app.get(), app.post(), app.put() and so on.

path- The path for which the routing function is invoked, Default is '/' (root path).

callback- A callback functions which will be executed when a matching path and request type is found. Routing methods can have more than one callback function as arguments.

GET method route example

Here is a simple GET method example using Express routing.

app.js

const express = require('express');
const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send("<h3>Hello World from ExpressJS</h3>")
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

As you can see here app.get(path, callback) method is used that routes HTTP GET requests to the specified path with the specified callback functions.

Specified path in our code is root path ('/'), callback function receives two arguments request and response. The request object (req) represents the HTTP request and the response object (res) represents the HTTP response.

Using res.send(body) function a HTTP response is sent back from the server.

You can run the application using the following command-

node app.js

Example app listening on port 3000

If you go to the URL http://localhost:3000/, server gets a GET request for the root path (‘/’) and executes the callback function which sends the "<h3>Hello World from ExpressJS</h3>" as response.

If you change the path in get method to ‘hello’

app.get('/hello', (req, res) => {
    res.send("<h3>Hello World from ExpressJS</h3>")
})

Then you'll get back the response when you hit the URL- http://localhost:3000/hello

POST method route example in Express

Here is a POST method example using Express routing. In the code there is a GET method route which sends a form as response with method as 'POST'. This request should be called first.

Once you have the form and you click the submit button that triggers the post request.

This example uses body-parser package which is used to parse the request body as we want to extract the entered name from the request.

App.js

const express = require('express');
const bodyParser = require('body-parser'); 

const app = express();
const port = 3000;

app.use(bodyParser.urlencoded({extended: true}));

app.get('/hello', (req, res) => {
    res.send('<form action="/name" method="post"><input type="text" name="name"><button type="submit">Submit</button></form>');
})

app.post('/name', (req, res) => {
    console.log(req.body.name);
    const name = req.body.name;
    res.send('<h3>Your name is ' + name + '</h3>');
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

If you go to the URL http://localhost:3000/hello, server gets a GET request for the path ('/hello') and executes the callback function which sends the form as response.

Enter a name and press submit which should send a POST request to the server. In the callback function name is extracted from the parsed request body and a response is sent to the user.

Here is another example showing the most popular HTTP methods GET, POST, PUT, PATCH and DELETE in use.

const express = require('express');

const app = express();
const port = 3000;

app.get('/', (req, res) => {
    res.send('Processing GET request');
})

app.post('/', (req, res) => {
    res.send('Processing POST request');
})

app.put('/', (req, res) => {
    res.send('Processing PUT request');
})

app.delete('/', (req, res) => {
    res.send('Processing DELETE request');
})

app.patch('/', (req, res) => {
    res.send('Processing PATCH request');
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

You can test it using curl command from terminal.

C:\>curl -X GET http://localhost:3000
Processing GET request

C:\>curl -X POST http://localhost:3000
Processing POST request

C:\>curl -X PUT http://localhost:3000
Processing PUT request

C:\>curl -X DELETE http://localhost:3000
Processing DELETE request

C:\>curl -X PATCH http://localhost:3000
Processing PATCH request

Refer this post express.Router() Function With Examples to see how to create module route definitions using express.Router() function.

Multiple callbacks with a request

You can provide multiple callback functions to handle a request. These callback functions must be separated by comma and make sure you specify the next object to go to the next callback.

app.get('/', (req, res, next) => {
    console.log('In first callback');
    next();
},
(req, res) => {
    res.send('From second callback');
}
)

Using regular expression with paths

You can use regular expressions while constructing paths.

Regular expression A? means A once or not at all.

For example-

app.get('/ab?cd', (req, res) => {
  res.send('ab?cd')
})

This route path will match acd and abcd.

Regular expression A+ means A one or more times

app.get('/ab+cd', (req, res) => {
  res.send('ab+cd')
})

This route path will match abcd, abbcd, abbbcd, and so on.

Regular expression A* means any number of characters after A

app.get('/ab*cd', (req, res) => {
  res.send('ab*cd')
})

This route path will match abcd, abxcd, abANYcd, ab123cd, and so on.

Using app.all() method

app.all() method matches all HTTP verbs which means same method will be called for GET, POST, PUT and so on.

The app.all() method is useful if you want to process some logic for any type of request.

For example, consider the following route

app.all('*', requireAuthentication, fetchUser)

It requires that all routes irrespective of path and type of HTTP request require authentication, and automatically load a user.

That's all for the topic ExpressJS Routing With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment