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.METHOD (PATH, HANDLER)
Where:
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.
There are a number of HTTP requests that can be made. The following table sums these up:
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')
next()
}, 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:
app.get('/', foo(request, response) {response.send('You are at the home page!')})
app.post('/', foo(request, response) {response.send('Post request recieved.')})
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.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved.