【vue】axios封装拦截


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、引入文件

  • mian.js 中引入
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>

相关推荐

  1. 【vue】axios封装拦截

    2024-04-25 19:32:02       28 阅读
  2. 2024 axios封装 包括请求拦截、错误码等

    2024-04-25 19:32:02       45 阅读
  3. 无人机拦截

    2024-04-25 19:32:02       41 阅读
  4. Spring中拦截WebSecurityConfigurerAdapter和Aop拦截区分

    2024-04-25 19:32:02       60 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-25 19:32:02       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-25 19:32:02       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-25 19:32:02       82 阅读
  4. Python语言-面向对象

    2024-04-25 19:32:02       91 阅读

热门阅读

  1. Electron vue 进程间消息通行

    2024-04-25 19:32:02       34 阅读
  2. LeetCode-数组中最长的方波

    2024-04-25 19:32:02       35 阅读
  3. history命令

    2024-04-25 19:32:02       32 阅读
  4. 为什么你的项目总延期?多半是没做好5件事

    2024-04-25 19:32:02       30 阅读
  5. 数据结构-分治策略(分治算法)

    2024-04-25 19:32:02       32 阅读
  6. 逆序对 题解 归并排序

    2024-04-25 19:32:02       22 阅读
  7. Android ContentProvider

    2024-04-25 19:32:02       30 阅读
  8. Kotlin语法入门-密封类和密封接口(11)

    2024-04-25 19:32:02       32 阅读
  9. MyBatis-动态sql常见使用

    2024-04-25 19:32:02       35 阅读