问题
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