人体解析器如何表达?

node.js Node.js

神奇番长神无

2020-03-18

我不明白为什么需要body-parserExpress应用程序,因为无需使用即可获取数据body-parser它实际上是做什么的?

第2077篇《人体解析器如何表达?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
LEY古一逆天 2020.03.18

要处理Express.js 4及更高版本中的HTTP POST请求,您需要安装名为的中间件模块body-parser

body-parser提取传入请求流的整个主体部分并将其公开req.body

中间件是Express.js的一部分,但现在您必须单独安装。

body-parser模块解析使用HTTP POST请求提交的JSON,缓冲区,字符串和URL编码的数据body-parser如下所示使用NPM 安装

npm install body-parser --save

在2019年4月2 日中进行编辑:在express@4.16.0中,与express捆绑在一起的body-parser中间件。有关更多详细信息,请参阅此

蓝染大人飞云 2020.03.18

为了访问帖子数据,我们必须使用body-parser基本上,什么body-parser是允许表达式读取主体,然后将其解析为Json我们可以理解对象。

杜大爷 2020.03.18

它解析HTTP请求正文。当您需要了解的不仅仅是击中的URL时,通常这是必需的,尤其是在POST或PUT PATCH HTTP请求的上下文中,其中您想要的信息包含在正文中。

基本上,它是一种用于解析JSON,纯文本或仅返回原始Buffer对象供您根据需要处理的中间件。

老丝Tom 2020.03.18

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对象,并用表单数据填充它。

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android