创建一个方法,导出这个方法就能给任一个页面使用
/*
*axios的用法:
*axios({
* method: 'post',
* url: '/user/12345',
* data: {
*
* }
*});
*/
//引入axios
import axios from 'axios'
//定义一个函数fetch,里面的参数:(url,data,method,headers)
const fetch = (url, data = {}, method = 'get', headers) => {
//创建一个配置json,到时直接当做是axios方法内的json参数
let options = {
url: url,
method: method,
data: data
}
//如果请求方式是get,在options内再加一个键 params
if (method === 'get') {
options.params = data
}
//如果有header,就将 options.headers = headers
if (headers) {
options.headers = headers
}
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
//如果相应的状态码是401,跳转到登录页
if (response.data.code === 401) {
window.location.href = window.location.origin + '/login'
}
//如果相应的状态码是403,弹出警告
else if (response.data.code === 403) {
alert(response.data.error)
window.location.href = window.location.origin
}
return response
}, function (error) {
//对响应错误做点什么
return Promise.reject(error)
})
return axios(options)
}
使用:
fetch('/upload/jqb/page/download/url-image', {}, 'POST')