繁体   English   中英

在节点JS表达请求中接收空对象

[英]Receive empty object in node js express request

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

我的代码错了吗?

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

由于其复杂且通常较大的性质,因此无法处理多部分实体。 对于多部分实体,您可能对以下模块感兴趣:

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

另外,您无需在fetch指定内容类型标头; 它会根据所提供的主体为您处理。

您不能按照文档中提到的形式对formData stringify处理

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

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

您可以考虑使用util-inspect尝试

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM