1.安装
npm install axios
2.使用
_axios.post("/api/auth/", form.value).then((res) => {
if (res.data.code === 0) {
// {id: 1, name: username.value, token: "xxx88sdkweisdfsd"}
store.doLogin(res.data.data)
router.push({name: "home"})
} else if (res.data.code === 1003) {
Object.keys(res.data.detail).forEach((k) => {
formError.value[k] = res.data.detail[k][0]
})
} else if (res.data.code === -1) {
ElMessage.error(res.data.detail)
}
})
3.拦截器
import axios from "axios";
import {userInfoStore} from "@/stores/counter.js";
import router from "@/router/index.js";
let config = {
baseURL: "http://127.0.0.1:8000",
timeout: 20 * 1000
}
const _axios = axios.create(config)
_axios.interceptors.request.use(function (config) {
// 1.去pinia中读取当前用户token
const info = userInfoStore()
// 2.发送请求携带token
if (info.userToken) {
if (config.params) {
config.params['token'] = info.userToken
} else {
config.params = {token: info.userToken}
}
}
return config;
})
// 根据状态码不同会走这两个函数:200成功走第一个,失败走第二个
_axios.interceptors.response.use(function (response) {
// console.log("拦截器", response)
// 认证失败
if (response.data.code === "1000") {
router.replace({name: "login"})
}
return response;
}, function (error) {
// console.log("拦截器异常", error)
if (error.response.data.code === "1000") {
router.replace({name: "login"})
// return error; // 执行成功
}
//...
return Promise.reject(error); //想后续的异常去传递,执行下个异常
})
export default _axios;
4.别忘了引入_axios
import _axios from "@/plugins/axios.js";
标签:拦截器,data,error,axios,&&,res,config,response
From: https://www.cnblogs.com/cloud-2-jane/p/18400061