不会说话,直接上代码
import axios from 'axios'
import { Message } from 'element-ui'
import Cookies from 'js-cookie';
axios.defaults.timeout = 10000;
//添加请求拦截器
axios.interceptors.request.use(config => {
config.headers.Authorization = 'new_global'
config.headers.Newglobal = 'new_global'
//配置方式调用axios
config = {
...config,
timeout: 100000,
withCredentials: true,
crossDomain: true,
}
return config
}, err => {
Promise.reject(err)
})
//添加响应拦截
axios.interceptors.response.use(response => {
const res = response.data
return res
}, err => {
let xtr = err.response.status
switch (xtr) {
case 401:
Message({
type: 'error',
message: '登录失效,请重新登录',
duration: 2 * 1000
})
localStorage.clear()
Cookies.remove('google_code')
setTimeout(() => {
window.location.href = '/#login'
location.reload()
}, 600)
break
case 400:
Message({
type: 'error',
message: '服务器请求错误',
duration: 2 * 1000
})
break
case 403:
Message({
type: 'error',
message: '您暂无权限操作该功能',
duration: 2 * 1000
})
break
break
case 404:
Message({
type: 'error',
message: '对不起,您请求资源不存在',
duration: 2 * 1000
})
break
case 500:
Message({
type: 'error',
message: '系统出错,稍后再试',
duration: 2 * 1000
})
break
case 504:
Message({
type: 'error',
message: '访问网络不好,请稍后',
duration: 2 * 1000
})
break
}
return Promise.reject(error.response);
})
// export default service
/**
* post方法,对应post请求
* @param {String} url [请求的url地址]
* @param {Object} sendObj [请求时携带的参数]
*/
export function post(url, sendObj) {
return new Promise((resolve, reject) => {
axios.post(url, sendObj).then(res => {
resolve(res);
}).catch(err => {
reject(err)
})
});
}
/**
* get方法,对应get请求
* @param {String} url [请求的url地址]
* @param sendObj 参数在请求的时候已经拼接到接口上
*/
export function get(url) {
return new Promise((resolve, reject) => {
axios.get(url).then(res => {
resolve(res);
}).catch(err => {
reject(err)
})
});
}
引入的话直接 import { post, get } from '@/utils/axios'
在接口文件里面使用:export const apiUrl = sendObj => post("/api/index",sendObj)
在vue文件里引入并使用 :
import { apiUrl } from '接口封装的文件地址'
apiUrl(sendObj).then(res =>{ }).catch(err => { })
get方法参数拼接方法:
export function getVal (params) {
let query = ''
for (let key in params) query += key + '=' + params[key] + '&'
query = query.slice(0, query.length - 1)
return query
}