文章目录
1、安装axios
typescript
npm install axios
2、新建文件
- 项目
src
目录创建util
文件夹 util
文件夹下创建文件axios.config.js
- 代码如下
typescript
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);
});
typescript
// 响应拦截
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、引入文件
mian.js
中引入
typescript
import "./util/axios.config"
4、使用
html
<template>
<div>帆帆帆帆帆帆帆帆帆帆帆帆帆帆</div>
</template>
typescript
<script setup lang="ts">
import axios from 'axios';
axios.get("/api/user/home").then((res) => {
console.log(res)
})
</script>