如何为 POST 设置 MIME 类型 - axios 中的多部分/表单数据?

IT技术 javascript reactjs axios
2021-05-07 03:42:59

我需要使用 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个回答

你可以试试这个:

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