【问题标题】:Receive empty object in node js express request在节点js快速请求中接收空对象
【发布时间】:2018-04-04 11:16:44
【问题描述】:

当我将图像从 react native 上传到节点 js 服务器时遇到问题,这是我的代码

客户

var url = "http://192.168.55.120:3000/uploadimg";
var file = this.state.imgsrc.uri;
const data = new FormData();
data.append('token', 'testName'); 
data.append('photo', {
  uri: file,
  type: 'image/jpeg', 
  name: 'testPhotoName'
});
fetch(url, {
  method: 'post',
  headers: {
    'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
    'Content-Type': 'multipart/form-data'
  },
  body: data
}).then(res => {
  console.log(res)
});

和我的服务器代码

const   express         = require('express'),
        bodyParser      = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.post('/uploadimg', function (req, res) {
    console.log(req.body); // =====> empty object       
})

我的代码错了?

【问题讨论】:

  • multer 是您需要处理 multipart/form-data npmjs.com/package/multer 的包,图像文件将位于 req.file 或 req.files
  • 也许我会尝试你的解决方案,谢谢,请发表答案,我会投票

标签: node.js express post react-native fetch


【解决方案1】:

您可以在body-parser docs 中签入,此包不处理多部分表单数据体。

这不处理多部分实体,因为它们的复杂性和 通常大的性质。对于多部分实体,您可能对 以下模块:

busboy and connect-busboy
multiparty and connect-multiparty
formidable
multer

另外,您不需要在fetch 中指定内容类型标头;它会根据提供的正文为您处理。

【讨论】:

    【解决方案2】:

    你不能像他们的docs中提到的那样stringifyformData

    使用FormData API是最简单最快的,但缺点是收集的数据不能被字符串化。

    如果要对提交的数据进行字符串化,请使用纯 AJAX 方法。

    你可以考虑用util-inspect试试

    【讨论】:

      猜你喜欢
      • 2015-08-23
      • 2020-03-27
      • 2023-01-29
      • 1970-01-01
      • 2017-03-22
      • 1970-01-01
      • 2015-09-18
      • 1970-01-01
      • 2017-08-19
      相关资源
      最近更新 更多