简体   繁体   English

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

[英]Receive empty object in node js express request

I have a problem when i upload image from react native to node js server, this is my code 当我将图像从本机上传到节点js服务器时出现问题,这是我的代码

Client 客户

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)
});

and my server code 和我的服务器代码

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       
})

My code is wrong ? 我的代码错了吗?

As you can check in body-parser docs , this package doesn't handle multipart form data bodies. 正如您可以在body-parser docs中检查的那样,此程序包不处理多部分表单数据主体。

This does not handle multipart bodies, due to their complex and typically large nature. 由于其复杂且通常较大的性质,因此无法处理多部分实体。 For multipart bodies, you may be interested in the following modules: 对于多部分实体,您可能对以下模块感兴趣:

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

Also, you shouldn't need to specify the content type header in fetch ; 另外,您无需在fetch指定内容类型标头; it'll handle it for you depending on the provided body. 它会根据所提供的主体为您处理。

You cannot stringify the formData as mentioned in their docs 您不能按照文档中提到的形式对formData stringify处理

Using the FormData API is the simplest and fastest, but has the disadvantage that data collected can not be stringified. 使用FormData API是最简单,最快的方法,但是具有无法对收集的数据进行字符串化的缺点。

If you want to stringify a submitted data, use the pure-AJAX method. 如果要对提交的数据进行字符串化,请使用pureAJAX方法。

You may consider trying it with util-inspect 您可以考虑使用util-inspect尝试

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

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