在节点js express请求中接收空对象

时间:2018-04-04 11:16:44

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

当我将图像从本机上传到节点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       
})

我的代码错了?

2 个答案:

答案 0 :(得分:1)

正如您可以检入body-parser docs,此程序包不处理多部分表单数据主体。

  

由于它们复杂而且不能处理多部分主体   通常是大自然。对于多部分机构,您可能感兴趣   以下模块:

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

此外,您不需要在fetch中指定内容类型标头;根据所提供的身体,它会为你处理它。

答案 1 :(得分:1)

docs

中提及的stringify formData不能
  

使用FormData API是最简单和最快速的,但缺点是收集的数据无法进行字符串化。

     

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

您可以考虑使用util-inspect

进行尝试