node.js body-parser 用 express 做什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38306569/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does body-parser do with express?
提问by jiten
I don't understand why we need body-parserin an Express application, as we can get data without using body-parser.
And what does it do actually and how?
我不明白为什么我们需要body-parser在 Express 应用程序中,因为我们可以在不使用body-parser. 它实际上做了什么以及如何做?
回答by Malatesh Patil
To handle HTTP POSTrequest in Express.jsversion 4 and above, you need to install middleware module called body-parser.
要处理Express.js版本 4 及更高版本中的HTTP POST请求,您需要安装名为.body-parser
body-parserextract the entire body portion of an incoming request stream and exposes it on req.body.
body-parser提取传入请求流的整个正文部分并将其公开req.body。
The middleware was a part of Express.js earlier but now you have to install it separately.
中间件之前是 Express.js 的一部分,但现在您必须单独安装它。
This body-parsermodule parses the JSON, buffer, string and URL encoded data submitted using HTTP POSTrequest. Install body-parserusing NPM as shown below.
该body-parser模块解析使用HTTP POST请求提交的 JSON、缓冲区、字符串和 URL 编码数据。body-parser使用 NPM安装,如下所示。
npm install body-parser --save
edit in 2019-april-2:in [email protected] the body-parser middleware bundled with express. for more details see this
2019 年 4 月 2 日编辑:在 [email protected] 中,与 express 捆绑的 body-parser 中间件。有关更多详细信息,请参阅此
回答by Himanshu sharma
Yes we can work without body-parser. When you don't use that you get the raw request, and your body and headers are not in the root object of request parameter . You will have to individually manipulate all the fields.
是的,我们可以在没有body-parser. 当您不使用它时,您将获得原始请求,并且您的正文和标头不在请求参数的根对象中。您将不得不单独操作所有字段。
Or you can use body-parser, as the express team is maintaining it .
或者您可以使用body-parser,因为快递团队正在维护它。
What body-parser can do for you: It simplifies the request.
How to use it: Here is example:
body-parser 可以为您做什么:它简化了请求。
如何使用它:这是示例:
Install npm install body-parser --save
安装 npm install body-parser --save
This how to use body-parser in express:
这是如何在 express 中使用 body-parser:
const express = require('express'),
app = express(),
bodyParser = require('body-parser');
// support parsing of application/json type post data
app.use(bodyParser.json());
//support parsing of application/x-www-form-urlencoded post data
app.use(bodyParser.urlencoded({ extended: true }));
Link.
关联。
https://github.com/expressjs/body-parser.
https://github.com/expressjs/body-parser。
And then you can get body and headers in root request object . Example
然后你可以在根请求对象中获取正文和标题。例子
app.post("/posturl",function(req,res,next){
console.log(req.body);
res.send("response");
})
回答by Suraj Jain
The answer hereexplain it very detailed and brilliantly, the answer contains:
这里的答案非常详细和出色地解释了它,答案包含:
In short; body-parserextracts the entire body portion of an incoming request stream and exposes it on
req.bodyas something easier to interface with. You don't need it per se, because you could do all of that yourself. However, it will most likely do what you want and save you the trouble.To go a little more in depth; body-parser gives you a middleware which uses nodejs/zlibto unzip the incoming request data if it's zipped and stream-utils/raw-bodyto await the full, raw contents of the request body before "parsing it" (this means that if you weren't going to use the request body, you just wasted some time).
After having the raw contents, body-parser will parse it using one of four strategies, depending on the specific middleware you decided to use:
bodyParser.raw(): Doesn't actually parse the body, but just exposes the buffered up contents from before in a Bufferon
req.body.bodyParser.text(): Reads the buffer as plain text and exposes the resulting string on req.body.
bodyParser.urlencoded(): Parses the text as URL encoded data (which is how browsers tend to send form data from regular forms set to POST) and exposes the resulting object (containing the keys and values) on
req.body. For comparison; in PHP all of this is automatically done and exposed in$_POST.bodyParser.json(): Parses the text as JSON and exposes the resulting object on
req.body.Only after setting the
req.bodyto the desirable contents will it call the next middleware in the stack, which can then access the request data without having to think about how to unzip and parse it.
简而言之; body-parser提取传入请求流的整个主体部分,并将其公开
req.body为更易于交互的内容。您本身不需要它,因为您可以自己完成所有这些。但是,它很可能会做您想做的事情并为您省去麻烦。更深入一点;body-parser 为您提供一个中间件,它使用nodejs/zlib来解压缩传入的请求数据(如果它被压缩)和stream-utils/raw-body 在“解析它”之前等待请求正文的完整原始内容(这意味着如果您不会使用请求正文,只是浪费了一些时间)。
获得原始内容后,body-parser 将使用四种策略之一对其进行解析,具体取决于您决定使用的特定中间件:
bodyParser.raw():实际上并不解析主体,而只是在Bufferon 中公开之前缓冲的内容
req.body。bodyParser.text():将缓冲区作为纯文本读取并在 req.body 上公开结果字符串。
bodyParser.urlencoded():将文本解析为 URL 编码数据(这是浏览器倾向于从设置为 POST 的常规表单发送表单数据的方式)并在 上公开结果对象(包含键和值)
req.body。作比较;在 PHP 中,所有这些都是自动完成的,并在$_POST.bodyParser.json():将文本解析为 JSON 并在 上公开结果对象
req.body。只有设置为
req.body想要的内容后,才会调用栈中的下一个中间件,然后该中间件就可以访问请求数据,而无需考虑如何解压和解析它。
You can refer to body-parsergithubto read their documentation, it contains information regarding its working.
您可以参考body-parser github来阅读他们的文档,它包含有关其工作的信息。
回答by Abzy
Let's try to keep this least technical.
让我们尽量保持这种最少的技术性。
Let's say you are sending a html form data to node-js server i.e. you made a request to the server. The server file would receive your request under a request object. Now by logic, if you console log this request object in your server file you should see your form data some where in it, which could be extracted then, but whoa ! you actually don't !
假设您正在向 node-js 服务器发送 html 表单数据,即您向服务器发出请求。服务器文件将在请求对象下接收您的请求。现在按照逻辑,如果您控制台将这个请求对象记录在您的服务器文件中,您应该在其中的某个位置看到您的表单数据,然后可以提取这些数据,但是哇!你实际上没有!
So, where is our data ? How will we extract it if its not only present in my request.
那么,我们的数据在哪里?如果它不仅出现在我的请求中,我们将如何提取它。
Simple explanation to this is http sends your form data in bits and pieces which are intended to get assembled as they reach their destination. So how would you extract your data.
对此的简单解释是 http 以零碎的形式发送您的表单数据,这些数据旨在在它们到达目的地时进行组装。那么你将如何提取数据。
But, why take this pain of every-time manually parsing your data for chunks and assembling it. Use something called “body-parser” which would do this for you.
但是,为什么每次都要手动解析数据块并组装它呢?使用一种叫做“body-parser”的东西,它会为你做这件事。
body-parser parses your request and converts it into a format from which you can easily extract relevant information that you may need.
body-parser 解析您的请求并将其转换为一种格式,您可以从中轻松提取您可能需要的相关信息。
For example, let's say you have a sign-up form at your frontend. You are filling it, and requesting server to save the details somewhere.
例如,假设您在前端有一个注册表单。您正在填写它,并请求服务器将详细信息保存在某处。
Extracting username and password from your request goes as simple as below if you use body-parser.
如果您使用 body-parser,从您的请求中提取用户名和密码就像下面一样简单。
var loginDetails = {
username : request.body.username,
password : request.body.password
};
So basically, body-parser parsed your incoming request, assembled the chunks containing your form data, then created this body object for you and filled it with your form data.
所以基本上,body-parser 解析你的传入请求,组合包含你的表单数据的块,然后为你创建这个 body 对象并用你的表单数据填充它。
回答by Deepak Patidar
It parses the HTTP request body. This is usually necessary when you need to know more than just the URL you hit, particular in the context of a POST or PUT PATCH HTTP request where the information you want is contains in the body.
它解析 HTTP 请求正文。当您需要知道的不仅仅是您点击的 URL 时,这通常是必要的,特别是在 POST 或 PUT PATCH HTTP 请求的上下文中,您想要的信息包含在正文中。
Basically its a middleware for parsing JSON, plain text, or just returning a raw Buffer object for you to deal with as you require.
基本上它是一个中间件,用于解析 JSON、纯文本,或者只是返回一个原始 Buffer 对象供您根据需要进行处理。
回答by Rich Werden
These are all a matter of convenience.
这些都是为了方便。
Basically, if the question were 'Do we needto use body-parser?' The answer is 'No'. We can come up with the same information from the client-post-request using a more circuitous route that will generally be less flexible and will increase the amount of code we have to write to get the same information.
基本上,如果问题是“我们需要使用body-parser吗?” 答案是不'。我们可以使用更迂回的路线从 client-post-request 中得出相同的信息,这通常不太灵活,并且会增加我们必须编写的代码量来获得相同的信息。
This is kind of the same as asking 'Do we needto use expressto begin with?' Again, the answer there is no, and again, really it all comes down to saving us the hassle of writing more code to do the basic things that express comes with 'built-in'.
这是一种同为询问“我们需要使用express到开始?再一次,答案是否定的,而且,实际上这一切都归结为让我们省去编写更多代码来完成“内置”表达的基本事情的麻烦。
On the surface - body-parsermakes it easier to get at the information contained in client requests in a variety of formats instead of making you capture the raw data streams and figuring out what format the information is in, much less manually parsing that information into useable data.
从表面上看 -body-parser更容易以各种格式获取客户端请求中包含的信息,而不是让您捕获原始数据流并确定信息的格式,更不用说手动将该信息解析为可用数据。
回答by Satish Kuppili
In order to get access to the post data we have to use body-parser. Basically what the body-parseris which allows express to read the body and then parse that into a Jsonobject that we can understand.
为了访问发布数据,我们必须使用body-parser. 基本上是什么body-parser允许 express 读取主体,然后将其解析为Json我们可以理解的对象。
回答by Himansh
Understanding Requests Body
了解请求正文
When receiving a POST or PUT request, the request body might be important to your application. Getting at the body data is a little more involved than accessing request headers. The request object that's passed in to a handler implements the ReadableStream interface. This stream can be listened to or piped elsewhere just like any other stream. We can grab the data right out of the stream by listening to the stream's 'data' and 'end' events.
The chunk emitted in each 'data' event is a Buffer. If you know it's going to be string data, the best thing to do is collect the data in an array, then at the 'end', concatenate and stringify it.
let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); // at this point, `body` has the entire request body stored in it as a string });
接收 POST 或 PUT 请求时,请求正文可能对您的应用程序很重要。获取正文数据比访问请求标头要复杂一些。传入处理程序的请求对象实现了 ReadableStream 接口。可以像任何其他流一样在其他地方收听或通过管道传输此流。我们可以通过监听流的 'data' 和 'end' 事件直接从流中获取数据。
每个“数据”事件中发出的块是一个缓冲区。如果您知道它将是字符串数据,那么最好的做法是将数据收集到一个数组中,然后在“末尾”将其连接并字符串化。
let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); // at this point, `body` has the entire request body stored in it as a string });
Understanding body-parser
理解身体解析器
As per its documentation
根据其文档
Parse incoming request bodies in a middleware before your handlers, available under the req.body property.
在处理程序之前在中间件中解析传入的请求正文,在 req.body 属性下可用。
As you saw in the first example, we had to parse the incoming request stream manually to extract the body. This becomes a tad tedious when there are multiple form data of different types. So we use the body-parser package which does all this task under the hood.
正如您在第一个示例中看到的,我们必须手动解析传入的请求流以提取正文。当有多个不同类型的表单数据时,这变得有点乏味。所以我们使用 body-parser 包来完成所有这些任务。
It provides four modules to parse different types of data
它提供了四个模块来解析不同类型的数据
After having the raw content body-parser will use one of the above strategies(depending on middleware you decided to use) to parse the data. You can read more about them by reading their documentation.
在拥有原始内容后,正文解析器将使用上述策略之一(取决于您决定使用的中间件)来解析数据。您可以通过阅读他们的文档来了解更多关于他们的信息。
After setting the req.bodyto the parsed body, body-parser will invoke next()to call the next middleware down the stack, which can then access the request data without having to think about how to unzip and parse it.
设置req.body为解析后的 body 后,body-parser 会调用next()栈向下调用下一个中间件,这样就可以访问请求数据,而无需考虑如何解压和解析。

