【问题标题】:req.body is empty in Node节点中的 req.body 为空
【发布时间】:2019-11-06 23:02:04
【问题描述】:

React (Client) 通过 axios 发送 post 数据。 但是节点服务器端的 req.body 是空的。 尝试使用正文解析器。但失败了。 attached client side here

attached server code here

This is client Axios part

【问题讨论】:

  • 因为我是初学者,所以无法发布代码。相反,我附上了 2 张显示代码的图像。请帮忙。我为此苦苦挣扎了 2 周。
  • 你能告诉我们你的 axios 请求吗?
  • 看起来您正在使用 mutipart/form-data 提交请求,并且您的节点正在解析 www-urlencoded。将 axios 中的请求内容类型更改为 www-urlencoded。
  • 谢谢你们。我会尝试....仅供参考,添加了 Axios 部分。请再看一遍好吗?

标签: node.js post request content-type


【解决方案1】:

body-parser 不支持解码 multipart/form-data。有大量的库可用于解析 multipart-form/data。

我知道formidable 库正在工作,使用它就像这样简单:

var form = new formidable.IncomingForm();

form.parse(req, function(err, fields, files) {

    console.log(`fields: ${fields} /n files: ${files}`)

});

【讨论】:

    【解决方案2】:

    它应该是请求中的 Content-Type。

    默认情况下,正文解析器“urlencoded”只处理以下内容:

    Content-Type: application/x-www-form-urlencoded;
    

    你可以这样设置类型:

    app.use(bodyParser.urlencoded({
      extended: true,
      type: 'multipart/form-data'
    }))
    

    但是你必须自己解析“原始身体”,因为身体解析器不支持多部分。

    【讨论】:

    • “原始正文”是指未解析的 http 正文。对于 x-www-form-urlencoded,它很简单(key1=value1&key2=value2)。对于多部分,它更复杂。示例:ec.haxx.se/http-multipart.html
    猜你喜欢
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 2021-05-05
    • 1970-01-01
    • 2017-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多