What are express.json() and express.urlencoded() in Express.js?
What are express.json() and express.urlencoded() in Express.js?
express.json()
and express.urlencoded()
are built-in middleware functions in Express.js that are used to parse incoming request bodies. Middleware functions in Express.js are used to process the data before it reaches the route handlers.
The express.json()
middleware is used to parse incoming requests with JSON payloads. Essentially, it takes the raw string of JSON data sent with the request and converts it into a JavaScript object. After parsing, the resulting object is attached to the req.body
property, making it accessible in the route handlers.
This middleware is based on the body-parser module, which was previously a separate middleware that needed to be installed, but since Express version 4.16.0, it has been re-integrated into Express itself. The express.json()
middleware only looks at requests where the Content-Type
header matches application/json
.
Here's an example of how to use express.json()
:
const express = require('express');
const app = express();
app.use(express.json());
app.post('/some-route', (req, res) => {
console.log(req.body); // req.body contains the parsed JSON object
});
The express.urlencoded()
middleware is used to parse incoming requests with URL-encoded payloads. This type of encoding is commonly used by HTML forms. When a form is submitted, the data is sent to the server as a URL-encoded string, which this middleware will parse and convert into a JavaScript object, accessible through req.body
.
The express.urlencoded()
middleware also comes from the body-parser module and has an option called extended
. When extended
is set to true
, the middle...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào