简体   繁体   English

Axios FormData()获取空对象

[英]Axios FormData() getting empty Object

Browser-side code 浏览器端代码

let data = new FormData();
data.append('file', file);
data.append('userId', userId);


axios.post(`${baseUrl}/uploadFile`, data, {headers: {'Content-Type':'multipart/form-data'}}).then((result) => console.log(result)).catch((err) => cb(err))

Server side code 服务器端代码

app.use((req, res, next) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, DELETE, PUT, PATCH, OPTIONS');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, api_key, Authorization'); 
    res.setHeader('Access-Control-Expose-Headers', 'Content-Range');
    next();
  }); 

app.use('/', express.static('public'))

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

I have tried almost everything but I always get an empty Object. 我已经尝试了几乎所有内容,但始终得到一个空对象。

The file is a pdf 该文件是pdf

Anyone can help? 有人可以帮忙吗?

You are sending multipart/form-data encoded data. 您正在发送multipart/form-data编码的数据。

You have: 你有:

 app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); 

ie

  • A decoder for URL encoded data URL编码数据的解码器
  • A decoder for JSON encoded data JSON编码数据的解码器

You don't have one for Multipart encoded data! 您没有一个用于Multipart编码的数据!

Now, since you are using it, see the documentation for body parser : 现在,由于您正在使用它,请参阅正文解析器的文档:

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 busboy和connect-busboy
  • multiparty and connect-multiparty 多方和连接多方
  • formidable 强大
  • multer multer

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

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