axios 请求中默认 headers 的 Content-Type
属性为 application/json
类型,这种类型在跨域时,浏览器会先发送 options
请求,如果服务器响应完全符合请求要求,浏览器则会发送真正的 post 请求。
而当 headers 的 Content-Type
属性是 application/x-www-form-urlencoded
时不会发送 options
请求,所以需要在 axios 请求拦截中配置 headers['Content-Type'] = 'application/x-www-form-urlencoded
。并将 post 的参数转换为序列化的 URL 形式,具体设置如下:
// qs 库,URL 参数与对象参数之间的互相转换// 这里只用到了 `stringify` 方法import { stringify } from 'qs';// 请求拦截axiosService.interceptors.request.use( (config) => { // 兼容 post 跨域问题 if (config.method === 'post') { // 修改 Content-Type config.headers['Content-Type'] = 'application/x-www-form-urlencoded'; // 将对象参数转换为序列化的 URL 形式(key=val&key=val) config.data = stringify(config.data); } return config; }, (error) => { console.log(error); return Promise.reject(error); });
Content-Type
参数配置只会出现在POST
与PUT
请求中。qs.parse
方法可以将 URL 参数解析成对象的形式。