简体   繁体   English

什么是 express.json() 和 express.urlencoded()?

[英]What are express.json() and express.urlencoded()?

I cannot find any documentation on express.json() and express.urlencoded() .我在express.json()express.urlencoded()上找不到任何文档。 What do each of them do exactly?他们每个人具体做什么?

Here is the explanation that should clear doubts on express.json() and express.urlencoded() and the use of body-parser.这是应该清除对express.json()express.urlencoded()以及使用 body-parser 的疑问的解释。 It took me some time to figure this out.我花了一些时间才弄清楚这一点。

  1. What is Middleware?什么是中间件? It is those methods/functions/operations that are called BETWEEN processing the Request and sending the Response in your application method.在您的应用程序方法中处理请求和发送响应之间调用的是那些方法/函数/操作。

  2. When talking about express.json() and express.urlencoded() think specifically about POST requests (ie the.post request object) and PUT Requests (ie the.put request object)在谈论express.json()express.urlencoded()时,请特别考虑 POST 请求(即 .post 请求对象)和 PUT 请求(即 .put 请求对象)

  3. You DO NOT NEED express.json() and express.urlencoded() for GET Requests or DELETE Requests. GET 请求或 DELETE 请求不需要express.json()express.urlencoded()

  4. You NEED express.json() and express.urlencoded() for POST and PUT requests, because in both these requests you are sending data (in the form of some data object) to the server and you are asking the server to accept or store that data (object), which is enclosed in the body (ie req.body ) of that (POST or PUT) Request对于 POST 和 PUT 请求,您需要express.json()express.urlencoded() ,因为在这两个请求中,您都在向服务器发送数据(以某些数据对象的形式)并且您要求服务器接受或存储该数据(对象),包含在该(POST 或 PUT)请求的主体(即req.body )中

  5. Express provides you with middleware to deal with the (incoming) data (object) in the body of the request. Express 为您提供了处理请求正文中的(传入)数据(对象)的中间件。

    a.一个。 express.json() is a method inbuilt in express to recognize the incoming Request Object as a JSON Object . express.json()是 express 内置的一种方法,用于将传入的请求 Object 识别为JSON Object This method is called as a middleware in your application using the code: app.use(express.json());此方法在您的应用程序中被称为中间件,使用以下代码: app.use(express.json());

    b.湾。 express.urlencoded() is a method inbuilt in express to recognize the incoming Request Object as strings or arrays . express.urlencoded()是 express 内置的一种方法,用于将传入的请求 Object 识别为字符串或 arrays This method is called as a middleware in your application using the code: app.use(express.urlencoded());此方法在您的应用程序中被称为中间件,使用以下代码: app.use(express.urlencoded());

  6. ALTERNATIVELY, I recommend using body-parser (it is an NPM package) to do the same thing.或者,我建议使用body-parser (它是一个 NPM 包)来做同样的事情。 It is developed by the same peeps who built express and is designed to work with express.它是由构建 express 的同一位窥视者开发的,旨在与 express 一起使用。 body-parser used to be part of express. body-parser 曾经是 express 的一部分。 Think of body-parser specifically for POST Requests (ie the.post request object) and/or PUT Requests (ie the.put request object).考虑专门针对 POST 请求(即 .post 请求对象)和/或 PUT 请求(即 .put 请求对象)的 body-parser。

  7. In body-parser you can do在 body-parser 你可以做

    // calling body-parser to handle the Request Object from POST requests var bodyParser = require('body-parser'); // parse application/json, basically parse incoming Request Object as a JSON Object app.use(bodyParser.json()); // parse application/x-www-form-urlencoded, basically can only parse incoming Request Object if strings or arrays app.use(bodyParser.urlencoded({ extended: false })); // combines the 2 above, then you can parse incoming Request Object if object, with nested objects, or generally any type. app.use(bodyParser.urlencoded({ extended: true }));

The json and urlencoded middleware are both part of bodyParser . jsonurlencoded中间件都是bodyParser的一部分。 This is what the README says:这是自述文件所说的:

bodyParser([options]) bodyParser([选项])

Returns middleware that parses both json and urlencoded .返回解析jsonurlencoded的中间件。 The options are passed to both middleware. options被传递给两个中间件。

bodyParser.json([options]) bodyParser.json([选项])

Returns middleware that only parses json .返回仅解析json的中间件。 The options are:选项包括:

  • strict - only parse objects and arrays strict - 仅解析对象和 arrays
  • limit <1mb> - maximum request body size limit <1mb> - 最大请求正文大小
  • reviver - passed to JSON.parse() reviver - 传递给JSON.parse()

bodyParser.urlencoded([options]) bodyParser.urlencoded([选项])

Returns middleware that only parses urlencoded with the qs module.返回仅使用qs模块解析urlencoded的中间件。 The options are:选项包括:

  • limit <1mb> - maximum request body size limit <1mb> - 最大请求正文大小

If you ask me "what is the difference between express.urlencoded({extended: false}) and express.json() ", well, the difference is:如果你问我“ express.urlencoded({extended: false})express.json()有什么区别”,那么区别是:

  • express.json()

If you use express.json() it will parse the body from post/fetch request except from html post form.如果您使用express.json()它将解析来自 post/fetch 请求的主体,除了html 后表单。 It wont parse information from the html post form:它不会解析来自 html表单的信息:

<form action="/" method="POST">
    <input type="text" name="username">
    <button>Submit</button>
</form>

For instance, if you fill the form with "dean_ilham" then submit it, Express wont have an idea what inside the body with this express code:例如,如果你用“dean_ilham”填写表格然后提交,Express 不会知道这个 express 代码在正文中是什么:

const express = require('express')
const app = express()

app.use(express.json())
// app.use(express.urlencoded({ extended: false }))
app.use(express.static("public"))


app.get("/", (req, res) => {
    res.sendFile("index.html")
})

app.post("/", (req, res) => {
    res.send(req.body)
})


const port = process.env.PORT || 3001
app.listen(port, () => {
    console.log(`Server Up in Port ${port}`);
})

It will send {} after you click submit.单击提交后,它将发送{} But if you uncommented app.use(express.urlencoded({extended: false})) , then you will get {"username": "dean_ilham"} .但是如果你取消注释app.use(express.urlencoded({extended: false})) ,那么你会得到{"username": "dean_ilham"}

So the difference is express.json() is a body parser for post request except html post form and express.urlencoded({extended: false}) is a body parser for html post form.所以不同之处在于express.json()html 后表单之外的 post 请求的正文解析器, express.urlencoded({extended: false})是 html 后表单的正文解析器。

What is Middleware什么是中间件

To understand what express.json and express.urlencoded do, you have to understand what middlewares are.要了解 express.json 和 express.urlencoded 的作用,您必须了解什么是中间件。

Middlewares are functions or methods in expressJS for carrying out various operations on requests made to the server.中间件是 expressJS 中的函数或方法,用于对向服务器发出的请求执行各种操作。

By now you should know how to get a request to a route using express.到目前为止,您应该知道如何使用 express 获取对路由的请求。

app.get("/api/houses", (req, res) => {
     console.log("Received request");
     res.send("houses")
   })

Importance of Middleware中间件的重要性

The above code is a typical example of how express handles a get request.上面的代码是 express 处理 get 请求的典型例子。 But in a situation whereby you want an operation to be carried on every request made to the server.但是在您希望对向服务器发出的每个请求进行操作的情况下。 You would not like to repeat codes in every route.您不想在每条路线中重复代码。

A middleware comes to the rescue at this stage.在这个阶段,一个中间件来救援。 The middleware acts like a general reciever for every request.中间件就像每个请求的通用接收器。

app.use((req, res, next) => {
      console.log("Verifing request"); 
      next();
     })

The above is a custom middleware that verifies every request made to my server and sends ad sends the request too the next appropriate routeing middleware depending on the type of request it.上面是一个自定义中间件,它验证对我的服务器发出的每个请求,并根据请求的类型发送广告并将请求发送到下一个适当的路由中间件。 (GET, POST, PUT etc.) (获取、发布、放置等)

Builtin Middleware内置中间件

Now expressJS has some already made middlewares which help developer in carrying out some tedious task.现在 expressJS 已经制作了一些中间件,可以帮助开发人员执行一些繁琐的任务。 like converting request body to JSON and so many others.比如将请求正文转换为 JSON 等等。

Examples of these builtin ExpressJS middlewares are这些内置 ExpressJS 中间件的示例是

  • express.json() express.json()
  • express.urlencoded() express.urlencoded()

express.json() is a built express middleware that convert request body to JSON. express.json()是一个内置的 express 中间件,将请求正文转换为 JSON。

express.urlencoded() just like express.json() converts request body to JSON, it also carries out some other functionalities like: converting form-data to JSON etc. express.urlencoded()就像 express.json() 将请求正文转换为 JSON 一样,它还执行一些其他功能,例如:将表单数据转换为 JSON 等。

This middleware is available in Express v4.16.0 onwards.此中间件在 Express v4.16.0 及更高版本中可用。

app.use(express.urlencoded({ extended: true}))

extended[boolean]: This option allows to choose between parsing the URL-encoded data with the querystring library (when false) or the qs library (when true). extended[boolean]:此选项允许在使用 querystring 库(如果为 false)或 qs 库(如果为 true)解析 URL 编码数据之间进行选择。 The “extended” syntax allows for rich objects and arrays to be encoded into the URL-encoded format, allowing for a JSON-like experience with URL-encoded “扩展”语法允许将丰富的对象和 arrays 编码为 URL 编码格式,从而实现类似 JSON 的 URL 编码体验

express docs:- https://expressjs.com/en/api.html#express.urlencoded快递文档:- https://expressjs.com/en/api.html#express.urlencoded

express.urlencoded() is required when you are submitting a form with post method ( default content-type = application/ x-www-form-urlencoded ) and you need to acess that form data using req.body, if you don't use it req.body would be undefined.当您使用 post 方法(默认 content-type = application/ x-www-form-urlencoded )提交表单时需要 express.urlencoded() 并且您需要使用 req.body 访问该表单数据,如果您不这样做使用它 req.body 将是未定义的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM