11

我已经阅读了我能找到的所有文档,但我找不到关于这两个中间件做什么的简单解释。

bodyinbody-parser指的是什么?为什么需要解析body?

Cookie 也是如此。我是否正确地cookie-parser“解析”或删除了伴随网络用户的 cookie?

最后,我读过body-parserExpress4 中不安全且已弃用的内容。我不应该使用它吗?

4

3 回答 3

13

As you may know, Node.js provides by default a very low level HTTP module. That's why you need "frameworks" like Express and such - they let you easily handle common features of web servers in other platforms (like Java and PHP, for example).

body-parser will take the body of your request and parse it to whatever you want your server to receive in POST/PUT requests (JSON, URL encoded, text, raw).
The only problem with body-parser (the far I know) is that you can't handle multipart bodies (which are commonly uploads).

cookie-parser will parse the Cookie header and handle cookie separation and encoding, maybe even decrypt it!

This all comes down to the fact that you don't need to use these features, and that's why Node is great.
You can simply ignore them and have your server less busy :)

于 2014-10-17T03:25:29.000 回答
8

在 Express 4 中,body-parsercookie-parser被移动到单独的模块中。不推荐使用的 body 和 cookie 解析器是 Express 3 附带的。

正文解析器解析请求正文。那些可能包含像 json 或 url 编码的表单数据。表单数据随后将出现在req.body.

cookie解析器解析cookie并将cookie信息放在req中间件的对象上。如果您知道秘密,它还将解密签名的 cookie。

于 2014-10-17T03:20:45.517 回答
0

这是文档的链接。它很好地解释了如何使用它,并且由于 express 4x 是一个内置的中间件功能,它与 body-parser 的工作相同,您可能不需要安装 body-parser。

于 2018-10-09T18:34:04.020 回答