创建ipConfig
用来配置开发接口地址和正式地址
var developmentUrl = ''
var productionUrl = ''
var ip = process.env.NODE_ENV === 'production' ? productionUrl : developmentUrl
export const devIp = ip
创建request.js
封装axios
import axios from 'axios'
import { Message } from 'element-ui'
import { devIp } from '@/api/ipConfig'
import router from '../router'
const service = axios.create({
baseURL: devIp, // 测试IP
timeout: 100000, // request timeout
headers: {
'Content-Type': 'application/json',
'TENANT-ID': '1',
},
// headers: { 'Content-Type': 'application/json' },
})
service.interceptors.request.use(config => {
let token = localStorage.getItem('access_token')
if (token) {
config.headers['Authorization'] = 'Bearer ' + token // 让每个请求携带token-- ['X-Token']为自定义key 请根据实际情况自行修改
}
return config
}, error => {
Promise.reject(error)
})
// respone interceptor
service.interceptors.response.use(
// response => response,
response => {
const res = response.data
// return res;
if (res.code == 0) {
return res
} else if (res.code == 100) {
if (res.message == 'token无效') {
localStorage.removeItem('token')
router.push({ path: '/login' })
} else if (res.message == '暂未有任何机器') {
} else {
Message({
message: res.message,
type: 'error',
duration: 2 * 1000
})
}
} else {
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
})
return res
}
},
error => {
// console.log('err' + error.response.status)// for debug
if (error.response.status == 401) {
localStorage.removeItem('token')
router.push({ path: '/login' })
}
Message({
message: error.msg,
type: 'error',
duration: 3000
})
return Promise.reject(error)
})
export default service
使用
import request from '../request'
import qs from 'qs'
// get
export function geturl (data) {
return request({
url: 'apiurl' + qs.stringify(data),
method: 'get'
})
}
// post
export function post (data) {
return request({
url: 'apiurl',
method: 'post',
data
})
}
// put
export function put (data) {
return request({
url: 'apiurl',
method: 'put',
data
})
}
// delete
export function deletes (data) {
return request({
url: 'apiurl',
method: 'delete',
data
})
}