1、安装axios
npm install axios
2、新建文件
- 项目
src
目录创建 util
文件夹 util
文件夹下创建文件 axios.config.js
- 代码如下
import axios from "axios";
axios.interceptors.request.use(function (config) {
const token = localStorage.getItem("token")
config.headers.Authorization = `Bearer ${token}`
return config;
}, function (error) {
return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
const { authorization } = response.headers
authorization && localStorage.setItem("token", authorization)
return response;
}, function (error) {
const { status, data } = error.response
if (status === 401) {
localStorage.removeItem("token")
location.reload()
} else {
ElMessage.error(data.msg || "系统出错")
}
return Promise.reject(error);
});
3、引入文件
import "./util/axios.config"
4、使用
<template>
<div>帆帆帆帆帆帆帆帆帆帆帆帆帆帆div>
template>
<script setup lang="ts">
import axios from 'axios';
axios.get("/api/user/home").then((res) => {
console.log(res)
})
</script>