TLDR
Introduction
Routing is an essential building box for building web applications. It is the web application’s response for a specific URI (or a path) endpoint that is requested from the front end.
Based on the HTTP method the application will respond in a certain way based on the backend logic.
It simply responds to what needs to happen when the user hits a specific endpoint.
In this blog post, we’ll see how to set up an express route, advance techniques, and best practices to use express routing for more scalable, maintainable web applications.
Setting up a simple express route
const express = require('express');
const app = express();
// Define a route handler for the root URL ('/')
app.get('/', (req, res) => {
res.send('Hello world!');
});
app.listen(3000, () => {
console.log('Server started on port 3000');
});
When you break down the above basic express js route code,
app
is an express.js instance.get
is the HTTP method in lowercase (other methodspost
,put
, anddelete
)./
is the root route path (like the home route).(req, res)
are handler functions (request and response are shortened toreq
andres
).res.send()
sends a simple response to the front end ( a string, object, or array).
Response methods
Other than res.send()
, there are lots of inbuild response methods in express, the following are mostly used response methods.
Through this res
you can access these methods based on our requirements.
res.json()
- sends a JSON response to the client.res.status()
- HTTP status code of the response. (ie:200
- success,404
- not found,500
- server error).
Request methods
Like response methods, the request also has inbuild methods to use. The following are mostly used response methods. You can access the request method by req
(req
is a short form of request
).
req.params
- to access the URL parameters in the API requestreq.query
- to access the query parameters.req.body
- to access the request body contains.
Hands-on code example
This code sample demonstrates how to use Express.js routing for CRUD functionality in the social media post route. (our main topic is route so the database implementation is ignored for the demo purpose)
// server.js - main server file
const express = require('express');
const app = express();
const postsRouter = require('./posts');
app.use('/api/posts', postsRouter);
app.listen(3000, () => {
console.log('Server started on port 3000');
});
// posts.js - handling post-related API calls
const express = require('express');
const router = express.Router();
router.get('/', (req, res) => {
// Implement logic to retrieve all posts from the database
res.send('All posts retrieved');
});
router.get('/:postId', (req, res) => {
const postId = req.params.postId;
// Implement logic to retrieve post by ID from database
res.send(`Post with ID ${postId} retrieved`);
});
router.post('/', (req, res) => {
// Implement logic to create new post in the database
res.send('New post created');
});
router.put('/:postId', (req, res) => {
const postId = req.params.postId;
// Implement logic to update post by ID in database
res.send(`Post with ID ${postId} updated`);
});
router.delete('/:postId', (req, res) => {
const postId = req.params.postId;
// Implement logic to delete post by ID from database
res.send(`Post with ID ${postId} deleted`);
});
module.exports = router;
By using the in-build method express.Router()
method you can modularize the related routing calls into separate files.
And you can access the specific postId
via req.params
. That will able to use get, update and delete the specific post.
Conclusion
In this blog post, we walk through the basic of express routing with mostly used routing methods in real-world applications. You can access the code used in this post via this https://github.com/ArjunMohan008/express-js-routing link.
For further reading check the official express documentation at https://expressjs.com/en/guide/routing.html
Happy learning/coding 😎