Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to do routing in express

Educative Answers Team

Routing determines how an application refers to client requests at a particular endpoint - URI (path) and HTTP request method.

Each route can have one or more handler functions executed.

These methods define a handler function that is called when the application receives a request to that specific route.

The route is defined using the following syntax,



  • app is an object of express.
  • METHOD is an HTTP request method, in lower case.
  • PATH is a path to the server.
  • HANDLER is the function executed when the path is matched.

Note: app.all( ) can be used to handle all HTTP requests.

HTTP Request methods

There are a number of HTTP requests that can be made. The following table sums these up:

svg viewer
MethodGetHeadPostPutDeleteTraceOptionsConnectPatchDescriptionRequests a specific resourceRequests just the headers of a resourceAsks the server to append the data to their resources such as formsRequests the accompanying entity be put at the specified URLDelete the specific resourceShows clients the changes made by intermediate serversReturns the HTTP requests server supportsConverts the request connection to transparent TCP/IPApplies partial modifications to resource.
HTTP methods

Handler Functions

Multiple callback functions can be defined to handle a request. They, however, may invoke next(‘route’) to bypass the remaining callbacks. These functions can be used to describe pre-conditions on a route and then pass them to subsequent routes.

app.get('/', function (request, response, next){
    console.log('Initial function')
}, function (request, response){
    request.send("Request received!")

The following examples show how the route can be defined to respond to different types of HTTP requests:

  1. HTTP GET request
app.get('/', foo(request, response) {
     response.send('You are at the home page!')
  1. HTTP POST request'/', foo(request, response) {
     response.send('Post request recieved.')
  1. HTTP PUT request
app.put('/user', foo(request, response){
     response.send('Object placed.')

Other HTTP requests can be similarly handled to perform specific tasks when they are called.


Copyright ©2022 Educative, Inc. All rights reserved

View all Courses

Keep Exploring