axios配置参数:
axios({
url: 'http://127.0.0.1:3000/users', // 请求的路径
method: 'get', // 请求方式
headers: { // 配置请求头
/* 在配置请求头,一些特殊字段 */
},
data: { // 设置请求的参数
name: 'aabb',
age: '18'
}
}).then((res) => {
console.log(res)
})
axios二次封装示例:
import axios from 'axios'
import config from './config.js'
import qs from 'qs'
export default function $axios (options) {
return new Promise((resolve, reject) => {
const instance = axios.create({
baseURL: config.baseURL,
headers: {},
transformResponse: [function (data) {}]
}
)
// request 拦截器
instance.interceptors.request.use(
config => {
if (config.method.toLocaleLowerCase() === 'post'
|| config.method.toLocaleLowerCase() === 'put'
|| config.method.toLocaleLowerCase() === 'delete') {
config.data = qs.stringify(config.data)
}
return config
},
error => {
if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
//这里可能会存在超时
// return service.request(originalRequest);
}
const errorInfo = error.response
console.log(errorInfo)
if (errorInfo) {
const errorStatus = errorInfo.status; // 404 403 500 ... 等
router.push({
path: `/error/${errorStatus}`
})
}
return Promise.reject(error)
}
)
// response 拦截器
instance.interceptors.response.use(
response => {
let data;
// IE9时response.data是undefined,因此需要使用response.request.responseText(Stringify后的字符串)
if(response.data == undefined){
data = response.request.responseText
} else{
data = response.data
}
// 根据返回的code值来做不同的处理(和后端约定)
switch (data.code) {
case '':
break;
default:
}
// 若不是正确的返回code,且已经登录,就抛出错误
// const err = new Error(data.description)
// err.data = data
// err.response = response
// throw err
return data
},
err => {
if (err && err.response) {
switch (err.response.status) {
case 400:
err.message = '请求错误'
break
case 401:
err.message = '未授权,请登录'
break
case 403:
err.message = '拒绝访问'
break
case 404:
err.message = `请求地址出错: ${err.response.config.url}`
break
case 408:
err.message = '请求超时'
break
case 500:
err.message = '服务器内部错误'
break
case 501:
err.message = '服务未实现'
break
case 502:
err.message = '网关错误'
break
case 503:
err.message = '服务不可用'
break
case 504:
err.message = '网关超时'
break
case 505:
err.message = 'HTTP版本不受支持'
break
default:
}
}
return Promise.reject(err)
}
)
instance(options)
.then((res) => {
resolve(res)
return false
})
.catch((error) => {
reject(error)
})
})
}