登录请求
import axios from 'axios'
import router from '../router'
let instance =axios.create({
// baseURL:'/api',
baseURL:'http://localhost:3000',
timeout:5000
})
//请求拦截
instance.interceptors.request.use(config=>{
//请求前的处理
if (localStorage.token) { // 判断是否存在token
config.headers.authorization = localStorage.token;
}else{
router.push({
path:'/login'
})
}
return config
})
//响应拦截
instance.interceptors.response.use(res=>{
//请求前的处理
return res
},err=>{
if(err.response.status == 401){
location.href = '/login'
}
return Promise.reject(err)
})
/**
* 用于请求的公共方法
* @param {*} option 配置项:method请求方法 path 路由 params 参数
*/
async function http(option = {}){
let result = null
if(!option.params){
option.params={}
}
// option.params.key = 'b38c2ee7024871f8e1c022b4f90d8088'
if(option.method === 'get' || option.method ==='delete'){
await instance[option.method](
option.path,
{
params:option.params
}
).then(res=>{
console.log('请求结果');
result =res.data
}).catch(err=>{
result = err
})
}else if(option.method==='post'||option.method==='patch' ||option.method==='put'){
await instance[option.method](
option.path,
option.params
).then(res=>{
result =res.data
}).catch(err=>{
result = err
})
}
return result
}
export default http
在main.js中引入
import http from './http'
Vue.prototype.$http = http