定义基于axios的request.js
import axios from "axios"
import router from "../router/index"
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout:10000
})
service.interceptors.request.use(
config => {
if(window.localStorage.getItem("token")){
config.headers.token = window.localStorage.getItem("token")
}
return config;
},
error => {
return Promise.reject(error);
}
);
service.interceptors.response.use(
response => {
const res = response
if(res.data.code == 20000){
return res
}else if(res.data.code == 90001){
router.replace("/")
return
}else{
return Promise.reject("Error")
}
},
error => {
return Promise.reject(error)
}
)
export default service
向后端发送请求
import request from "../utils/request"
login(name,password){
return request({
url: "v1/login",
method: "post",
data: {
name: name,
password: password
}
})
}