All You Need To Know About Routing in The Express Framework For Node - Js
All You Need To Know About Routing in The Express Framework For Node - Js
js explained
All you need to know about routing in the Express Framework
for Node.js
This article is part of a large series about Express.js. You can find all
articles here — Express Framework.
Routing in Express
Route methods
• GET .get()
• POST .post()
• PUT .put()
• DELETE .delete()
• PATCH .patch()
Route paths
This route path will match requests made to /acd and /abcd.
app.get('/ab?cd', (req, res) => {
res.send('ab?cd');
});
This route path will match requests made to abcd, abbcd, abbbcd, etc.
app.get('/ab+cd', (req, res) => {
res.send('ab+cd');
});
Express 4.x treats the * differently, see here. This behaviour is fixed
since Express 5.x.
Route parameters
Route handlers
Route handlers are callback functions or arrays of functions, which
basically handle requests. Multiple callback functions can be provided
to handle a request and behave like a middleware. The only exception
is that these callbacks can call next() to bypass the next and remaining
route callbacks. Route handlers can be in the form of a function, an
array of functions, or a combination of both.
The request and response are often shortened to req and res, and stand
for the request which was received by the server, and the response
which will eventually be send back.
• The server receives the request, reads the data (request headers,
URL path, HTTP method, query parameters, cookies, data or
payload, etc.).
• Once the response has been sent back, the HTTP transaction is
completed.
Augmenting the req and res objects is a big part of how Express
enhances functionality, while still maintaining control over how
requests and responses are handled.
Response methods
The methods on the response object (res) in the following table can
send a response to the client, and terminate the request-response cycle.
If none of these methods are called from a route handler, the client
request will be left hanging.
• res.sendStatus() Set the response status code and send its string
representation as the response body.
With app.route() you can chain route handlers for a route path.
Creating modular routes is helpful, because it is reducing redundancy
and typos.
TL;DR
• Route paths, in combination with a request method, define the
endpoints at which requests can be made. A Route definition takes
the following structure: app.METHOD(PATH, HANDLER)
If you want to know more about Express, have a look at these Express
Tutorials.