Axios FormData()获取空对象 [英] Axios FormData() getting empty Object

查看:505
本文介绍了Axios FormData()获取空对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

浏览器端代码

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

服务器端代码

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.

文件为pdf

任何人都可以帮忙吗?

推荐答案

您正在发送multipart/form-data编码的数据.

You are sending multipart/form-data encoded data.

您有:

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

  • 用于URL编码数据的解码器
  • 用于JSON编码数据的解码器

您没有一个用于Multipart编码的数据!

You don't have one for Multipart encoded data!

现在,由于您正在使用它,请参阅 body解析器的文档:

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

这篇关于Axios FormData()获取空对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆