axios 默认是 Payload 格式数据请求,但有时候后端接收参数要求必须是 Form Data 格式的,所以我们就得进行转换。Payload 和 Form Data 的主要设置是根据请求头的 Content-Type 的值来的。
Payload Content-Type: ‘application/json; charset=utf-8’
Form Data Content-Type: ‘application/x-www-form-urlencoded’
axios_5">封装axios
//示例
api 目录下有两个文件 index.js 与 config.js
//调用
import api from 'xxx/api'
api.getName({}).then((res)=>{
console.log(res,'返回值')
})
index.js
import {fetch} from './config.js';
export default {
getName(params){return fetch('coupon','getName',params,'post')},
}
config.js
import axios from 'axios'
import qs from 'qs'
axios.defaults.timeout = 60000; //响应时间
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'; //配置请求头
//配置接口地址
axios.defaults.baseURL = 'https://jdbb.shuimuglobal.com/';
//请求拦截
axios.interceptors.request.use((config)=>{
console.log(config,'config')
return config
});
//请求后
axios.interceptors.response.use((res) => {
return res
});
//请求前
export function fetch(_gp, _mt, params,type) {
return new Promise((resolve, reject) => {
if(type=='post'){
axios.post('/jfmall/m.api',qs.stringify({...params,_gp, _mt} ))
.then(response => {
resolve(response.data);
}, err => {
reject(err);
})
.catch((error) => {
reject(error)
})
} else {
// resolve(url)
resolve(axios.defaults.baseURL + url);
}
})
}
在封装 axios 的时候,设置请求头 Content-Type 为 application/x-www-form-urlencoded。 然后在请求拦截器中,通过 qs.stringify() 进行数据格式转换,这样每次发送的POST请求都是 Form Data 格式的数据了。 其中 qs 模块是安装 axios 模块的时候就有的,不用另行安装,通过 import 引入即可使用。