import Axios from 'axios'
import { Toast } from 'vant';
import { Notification, MessageBox, Message } from 'element-ui'
import router from "../router/index";
import store from '../store';
import storage from './storage_helper'
class Request {
constructor () {
// 创建axios实例
const axios = Axios.create({
baseURL : process.env.API_HOST ,
timeout : 10000
})
//头部文件
axios.defaults.headers['Content-Type'] = 'application/json;charset=utf-8'
// request拦截器
axios.interceptors.request.use(config => {
// 是否需要设置 token
const getToken=storage.getItem("token")
console.log("getToken",store.state.store.token)
const isToken = (config.headers || {}).isToken === false
if (getToken && !isToken) {
config.headers['Authorization'] = getToken // 让每个请求携带自定义token 请根据实际情况自行修改
}
// get请求映射params参数
if (config.method === 'get' && config.params) {
let url = config.url + '?';
for (const propName of Object.keys(config.params)) {
const value = config.params[propName];
var part = encodeURIComponent(propName) + "=";
if (value !== null && typeof(value) !== "undefined") {
if (typeof value === 'object') {
for (const key of Object.keys(value)) {
let params = propName + '[' + key + ']';
var subPart = encodeURIComponent(params) + "=";
url += subPart + encodeURIComponent(value[key]) + "&";
}
} else {
url += part + encodeURIComponent(value) + "&";
}
}
}
url = url.slice(0, -1);
config.params = {};
config.url = url;
}
return config
}, error => {
console.log(error)
Promise.reject(error)
})
//响应拦截器
axios.interceptors.response.use(res=>{
//未设置状态码则默认成功状态
const code =res.data.code||200
console.log("code",code)
//获取错误信息
const msg = res.data.msg
if(code===401){
MessageBox.confirm('登录状态已经过期,您可以继续留在该页面,或者重新登陆','系统提示',{
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}).then(()=>{
storage.remove("token")
// store.dispatch('login').then(()=>{
router.replace('/')
return;
// this.$message({
// type:'success',
// message:'登陆成功'
// });
// })
}).catch(()=>{
})
}else if(code===500){
Message({
message: msg,
type: 'error'
})
return Promise.reject(new Error(msg))
}else if(code !==200){
Notification.error({
title: msg
})
return Promise.reject('error')
}else{
console.log(res)
return res
}
},error=>{
console.log('err' + error)
let { message } = error;
if (message == "Network Error") {
message = "后端接口连接异常";
}
else if (message.includes("timeout")) {
message = "系统接口请求超时";
}
else if (message.includes("Request failed with status code")) {
message = "系统接口" + message.substr(message.length - 3) + "异常";
}
Message({
message: message,
type: 'error',
duration: 5 * 1000
})
console.log(error)
return Promise.reject(message)
})
// this.appkey = ''
this.axios = axios
}
get (url, params = {}) {
if (!params.headers) {
params.headers = {}
}
return new Promise((resolve, reject) => {
this.axios.get(url, params).then(res => {
res = res.data
if (res.code === 200) {
let data=null
if(res.data){
console.log("requset",res)
data = res.data
}
else{
data = res.msg
Toast(data)
}
resolve(data)
} else {
Toast(res.msg)
reject(res.msg)
}
}).catch(err => {
// Toast(err)
reject(err)
})
})
}
post (url, data, headers = {}) {
return new Promise((resolve, reject) => {
this.axios({
method: 'post',
url,
data,
headers
}).then(res => {
if (res.status === 200) {
res = res.data
resolve(res)
} else {
reject(res.statusText)
}
}).catch(err => {
reject(err)
})
})
}
}
export default Request
request拦截器
最新推荐文章于 2024-09-03 10:55:56 发布
这篇博客详细介绍了如何在Vue项目中使用axios进行API请求的封装,包括设置基础URL、请求头、请求和响应拦截器,以及处理各种错误情况。作者通过示例展示了如何处理401未授权和500服务器错误,并展示了如何在请求中映射GET请求的参数。
摘要由CSDN通过智能技术生成