如何设置POST的MIME类型-axios中的multipart / form-data?

时间:2019-04-06 15:55:49

标签: javascript reactjs axios

我需要发送带有MIME的POST请求-multipart/form-data

这是我的POST标头的默认配置: axios.defaults.headers.post['Content-Type'] = 'multipart/form-data';

我希望默认的Content-Type应该是multipart/form-dat,但是在chrome devtools中,我看到Content-Type: application/json

1 个答案:

答案 0 :(得分:1)

您可以尝试以下方法:

const data = new FormData();

data.append('action', 'ADD');
data.append('param', 0);
data.append('secondParam', 0);
data.append('file', new Blob(['test payload'], { type: 'text/csv' }));

axios.post('http://httpbin.org/post', data);

此代码正在使用FormData API

另一个选择是使用form-data软件包:

const axios = require('axios');
const FormData = require('form-data');

const form = new FormData();
// Second argument  can take Buffer or Stream (lazily read during the request) too.
// Third argument is filename if you want to simulate a file upload. Otherwise omit.
form.append('field', 'a,b,c', 'blah.csv');
axios.post('http://example.org/endpoint', form, {
  headers: form.getHeaders(),
}).then(result => {
  // Handle result…
  console.log(result.data);
});