我不明白为什么需要body-parser
Express应用程序,因为无需使用即可获取数据body-parser
。它实际上是做什么的?
人体解析器如何表达?
为了访问帖子数据,我们必须使用body-parser
。基本上,什么body-parser
是允许表达式读取主体,然后将其解析为Json
我们可以理解的对象。
它解析HTTP请求正文。当您需要了解的不仅仅是击中的URL时,通常这是必需的,尤其是在POST或PUT PATCH HTTP请求的上下文中,其中您想要的信息包含在正文中。
基本上,它是一种用于解析JSON,纯文本或仅返回原始Buffer对象供您根据需要处理的中间件。
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 !
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.
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 parses your request and converts it into a format from which you can easily extract relevant information that you may need.
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.
var loginDetails = {
username : request.body.username,
password : request.body.password
};
因此,基本上,body-parser解析您的传入请求,组装包含表单数据的块,然后为您创建此body对象,并用表单数据填充它。
要处理Express.js 4及更高版本中的
HTTP POST
请求,您需要安装名为的中间件模块。body-parser
body-parser
提取传入请求流的整个主体部分并将其公开req.body
。中间件是Express.js的一部分,但现在您必须单独安装。
此
body-parser
模块解析使用HTTP POST
请求提交的JSON,缓冲区,字符串和URL编码的数据。body-parser
如下所示使用NPM 安装。在2019年4月2 日中进行编辑:在express@4.16.0中,与express捆绑在一起的body-parser中间件。有关更多详细信息,请参阅此