官方文档
官方文档说post请求默认值是以表单形式提交的。
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
问题
我需要发送表单,但是我我发送的post的请求都是application/json
。
解决办法
官方文档虽然默认设置post请求是application/x-www-form-urlencoded
,但是它本身并没有提供编码表单的函数,也就是说需要自己写,如果自己没有写,那么它依然是application/json
方式提交。
最简单实现,全局配置:
transformRequest: [function (data) {
// 对 data 进行任意转换处理
let str = '';
for (const key in data) {
str += encodeURIComponent(key) + '=' + encodeURIComponent(data[key]) + '&'
}
return str.slice(0, str.length - 1);
}],
不仅仅是表单编码,所有其它的功能都需要自己配置。