Câu hỏi phỏng vấn Nodejs
Câu hỏi

What are express.json() and express.urlencoded() in Express.js?

Câu trả lời

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.

express.json()

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():

javascript Copy
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
});

express.urlencoded()

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

middle

Gợi ý câu hỏi phỏng vấn

expert

How would you implement process communication when using cluster module in Node.js?

senior

What is the difference between the child_process spawn and execute functions in Node.js? When to
use each one?

junior

What is the file package.json ?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào