In this tutorial, we'll be discussing how to work with JSON data in Express.js and how to implement middleware to handle various tasks. We'll cover how to parse incoming request bodies in a JSON format and use middleware for tasks like logging and error handling.
By the end of this tutorial, you will be able to:
- Parse JSON data from requests in Express.js
- Implement middleware in Express.js
- Use middleware for logging and error handling
Prerequisites:
- Basic knowledge of JavaScript
- Familiarity with Node.js and Express.js would be helpful
JSON (JavaScript Object Notation) is a popular data format with diverse uses in data interchange, including that of web applications. In Express.js, we can send JSON data using the res.json()
function.
res.json({ name: "John", age: 30 });
Middleware functions are functions that have access to the request object (req), the response object (res), and the next function in the application’s request-response cycle. The next function is a function in the Express router which, when invoked, executes the middleware succeeding the current middleware.
Middleware functions can execute any code, make changes to the request and the response objects, end the request-response cycle, and call the next middleware in the stack.
Middleware can be used to log details of every request that gets made to the server, and can also be used to handle errors.
Express.js has a built-in middleware function, express.json()
, to parse incoming request bodies in JSON format.
const express = require('express');
const app = express();
app.use(express.json());
app.post('/', (req, res) => {
console.log(req.body); // This will log the JSON request body to the console
res.json(req.body); // This will send the JSON request body as response
});
app.listen(3000, () => console.log('Server started on port 3000'));
This is a simple logging middleware that logs the details of every request made to the server.
app.use((req, res, next) => {
console.log(`${req.method} request for '${req.url}'`);
next();
});
This is a simple error handling middleware.
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
In this tutorial, we covered how to parse JSON data from requests in Express.js, how to implement middleware, and how to use middleware for logging and error handling.
To further your learning, you may want to look into:
- More ways to use middleware in Express.js
- How to structure your Express.js applications
- How to handle different types of errors in Express.js
Hint: To trigger an error, you can create a route that throws an error, like so:
app.get('/error', (req, res, next) => {
next(new Error('This is an error'));
});