📅  最后修改于: 2023-12-03 14:41:05.158000             🧑  作者: Mango
express.json
is a method in the Express framework that parses incoming JSON requests.
JSON (JavaScript Object Notation) is a lightweight data exchange format commonly used in web applications. When a client sends a JSON object in a request, the server needs to parse the JSON object to access the data therein. express.json
is the middleware that parses incoming JSON requests and sets the req.body
object with the parsed JSON object.
express.json
comes bundled with the Express framework. To use it, simply install Express using npm:
npm install express
const express = require('express');
const app = express();
// parse application/json
app.use(express.json());
app.post('/api/users', (req, res) => {
console.log(req.body); // { name: 'John', age: 25 }
res.send('User created successfully!');
});
app.listen(3000, () => {
console.log('Server started at http://localhost:3000');
});
The above code snippet parses the JSON object in the incoming request and sets the parsed JSON object in the req.body
object. Hence, req.body
can be accessed from within the route handler and the server can proceed to create a new user with the parsed data.
express.json
is a useful middleware in the Express framework that parses incoming JSON requests. It simplifies the process of handling incoming JSON data and allows the server to parse it with ease.