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



我需要使用 MIME 发送 POST 请求 - multipart/form-data

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

我希望默认Content-Type应该是multipart/form-dat,但在 chrome 开发工具中,我看到了Content-Type: application/json

你可以试试这个:

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

另一种选择是使用表单数据包:

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

最新更新