Axios FormData() getting empty Object

本秂侑毒 提交于 2020-08-10 19:00:30

问题


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

Anyone can help?


回答1:


You are sending multipart/form-data encoded data.

You have:

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

i.e.

  • A decoder for URL encoded data
  • A decoder for JSON encoded data

You don't have one for Multipart encoded data!

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
  • multiparty and connect-multiparty
  • formidable
  • multer


来源:https://stackoverflow.com/questions/53555705/axios-formdata-getting-empty-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!