清空req.body接收对node.js的text/plain POST请求

pan*_*ake 6 post http node.js

为什么我不能收到POST请求正文中发送的纯文本?

从客户端浏览器发出的请求:

var xhr = new XMLHttpRequest();
xhr.open("POST", "/MyRoute/MySubRoute");
xhr.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");
xhr.send("hello!");    
Run Code Online (Sandbox Code Playgroud)

在我的节点服务器上使用Express:

app.post('/MyRoute/MySubRoute', function(req, res) {
    console.log("Received:"+require('util').inspect(req.body,{depth:null});
    res.send();
});
Run Code Online (Sandbox Code Playgroud)

登录到控制台我得到:

Received:{}
Run Code Online (Sandbox Code Playgroud)

我试过text/plain(没有charset),结果相同.如果我将我的内容类型更改为application/json并传递一个简单的JSON字符串,它可以正常工作.

pan*_*ake 14

总结以上回答问题的评论:

  • 客户端的XMLHttpRequest是正确的
  • 在服务器端,Express使用connect的bodyParser,默认情况下仅支持以下内容类型:
    • 应用程序/ JSON
    • 应用程序/ x-WWW窗体-urlencoded
    • 多部分/格式数据
  • 因为Express没有实现text/plain的内容类型,所以没有方法在调用app/post路由之前等待接收正文.
  • 解决的办法是添加text/plain的内容类型,以快速的描述在这里