发布:2022/3/22 10:27:01作者:管理员 来源:本站 浏览次数:971
import store from '../store'
import axios from 'axios'// 引入axios
// 环境的切换 开发环境(development)使用的是测试接口 和 生产环境(production)使用的是上线接口
// eslint-disable-next-line eqeqeq
if (process.env.NODE_ENV == 'development') {
// 设置默认路径
axios.defaults.baseURL = 'http://localhost:8080/'
}
// eslint-disable-next-line eqeqeq
if (process.env.NODE_ENV == 'production') {
axios.defaults.baseURL = 'https://www.begon.cn/'
}
axios.defaults.timeout = 5000 // 加载不出来5秒之后就是加载失败
axios.interceptors.request.use(
config => {
config.headers = { DeviceType: 'ejk5', token: store.state.Authorization } // 可每次发送请求之前的逻辑处理 比如判断token
return config
}
)
// axios.interceptors.response.use(
// response=>{
// return response;
// },
// error=>{
// if(error.response.status){
// }
// }
// )
// 使用promise返回axios请求的结果
export function get (url, params) {
return new Promise((resolve, reject) => {
axios.get(url, {
params: params
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
};
export function getToken (url, params) {
console.log(store.state.Authorization)
return new Promise((resolve, reject) => {
axios.get(url, {
params: params,
headers: {token: store.state.Authorization, authorization: store.state.Authorization}
}).then(res => {
resolve(res)
}).catch(err => {
reject(err)
})
})
};
export function post (url, params) {
return new Promise((resolve, reject) => {
axios.post(url, params).then(res => {
resolve(res.data)
}).catch(err => {
reject(err.data)
})
})
}
export function postToken (url, params) {
return new Promise((resolve, reject) => {
// eslint-disable-next-line func-call-spacing
axios.post
// eslint-disable-next-line no-unexpected-multiline
(
url,
params,
{
headers: {'token': store.state.Authorization}
}
).then(res => {
resolve(res.data)
}).catch(err => {
reject(err.data)
})
})
}
// post请求
export function postRequest (url, data = {}, method = 'post') {
return new Promise((resolve, reject) => {
axios({
url: url,
method: method,
headers: {
'Content-Type': 'application/json'
},
data: data
})
.then(res => {
// 成功
resolve(res.data)
})
.catch(res => {
// 失败
reject(res)
})
})
}
// 添加请求拦截器,在请求头中加token
axios.interceptors.request.use(
config => {
if (localStorage.getItem('Authorization')) {
config.headers.Authorization = localStorage.getItem('Authorization')
}
return config
},
error => {
return Promise.reject(error)
})
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4