搭配elmentui使用的axios拦截器

import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '../store'
import { getToken } from '@/utils/auth'

// 创建axios实例
const service = axios.create({
    baseURL: `/v-api`,
    timeout: 15000,
})

// request拦截器
service.interceptors.request.use(
    config => {
        if (store.getters.token) {
            config.headers['Authorization'] = `Bearer ${getToken()}` // 让每个请求携带自定义token
        }
        // console.log(config)
        return config
    },
    error => {
        // Do something with request error
        console.log(error) // for debug
        Promise.reject(error)
    }
)

//response 拦截器
service.interceptors.response.use(
    response => {

        if (response.status == '401') {
            Message({
                message: '用户无权限!',
                type: 'warning'
            });
            // store.dispatch('FedLogOut').then(() => {
            //     location.reload()
            // })
            return Promise.reject('error')
        }
        if (response.status == '203') {
            MessageBox.confirm(
                '你已被登出,可以取消继续留在该页面,或者重新登录',
                '确定登出', {
                    confirmButtonText: '重新登录',
                    cancelButtonText: '取消',
                    closeOnPressEscape: false,
                    closeOnClickModal: false,
                    type: 'warning'
                }
            ).then(() => {
                store.dispatch('FedLogOut').then(() => {
                    location.reload()
                })
            })

            return Promise.reject('error')
        }
        const res = response.data
        if (res.code && res.code != '200') {
            if (res.code == '504') {
                MessageBox.confirm(
                    '你已被登出,可以取消继续留在该页面,或者重新登录',
                    '确定登出', {
                        confirmButtonText: '重新登录',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                ).then(() => {
                    store.dispatch('FedLogOut').then(() => {
                        location.reload()
                    })
                })
            } else if (res.code == '-1') {
                Message({
                    message: '程序繁忙,请稍后再试!',
                    type: 'error',
                    duration: 5 * 1000
                })
            } else if (res.code == '201') {

                MessageBox.alert(
                    '提示:' + res.message,
                    '', {
                        type: 'warning'
                    }
                )
                return res
            } else if (res.code == '204') {
                return res
            } else {
                Message({
                    message: '操作错误, ' + res.message,
                    type: 'error',
                    duration: 5 * 1000
                })
            }
            return Promise.reject('error')
        } else {

            return res

        }

    },
    error => {
        // console.log('err' + error) // for debug

        Message({
            message: error.response.data.message || '网络错误,请联系管理员!',
            type: 'error',
            duration: 5 * 1000
        })
        if (error.response.data.code == '416') {
            MessageBox.confirm(
                '用户信息过期,请重新登录',
                '确定登出', {
                    confirmButtonText: '重新登录',
                    showCancelButton: false,
                    type: 'warning'
                }
            ).then(() => {
                store.dispatch('FedLogOut').then(() => {
                    location.reload()
                })
            })
        }

        return Promise.reject(error.response.data) // 返回接口返回的错误信息
    })



export default service

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 请问您的问题是如何在Vue3中使用axios拦截器来添加token吗?如果是这样的话,可以通过以下代码来实现: 首先,在main.js中引入axios和设置拦截器: import axios from 'axios'; // 设置baseUrl axios.defaults.baseURL = 'http://localhost:8000/'; // 设置拦截器 axios.interceptors.request.use( config => { const token = localStorage.getItem('token'); if (token) { config.headers.authorization = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); } ); 然后,您可以在代码中使用axios请求,并且该请求中会自动带上token: // 发起一个有token的GET请求 axios.get('/api/user').then(response => { console.log(response); }).catch(error => { console.log(error); }); ### 回答2: 在Vue3中使用axios拦截器来为每个HTTP请求设置token是一种常见实践。Axios拦截器可以帮助我们在请求发送之前或响应返回之前拦截,并在拦截器中添加必要的数据,如token。为了在Vue3中使用Axios拦截器为每个HTTP请求设置token,下面的内容将提供一些具体方法。 首先,我们需要安装Axios和Vue3,安装方法为: ```vue3 # 安装vue3 npm i vue@next -S # 安装axios npm i axios -S ``` 然后,我们需要在Vue3应用中创建一个Axios实例,代码如下: ```vue3 import axios from 'axios'; const api = axios.create({ baseURL: 'http://localhost:3000', }); export default api; ``` 在应用程序中,我们可以在需要发送HTTP请求的组件中导入并使用此api实例。 接下来,我们需要在Axios实例中创建一个拦截器拦截器拦截HTTP请求并在其中添加必要的headers。在这里,我们添加一个头部,它包含一个名为“Authorization”的令牌。代码如下: ```vue3 api.interceptors.request.use((config) => { config.headers.Authorization = 'Bearer ' + localStorage.getItem('token'); return config; }); ``` 通过使用这个拦截器,我们可以在每个HTTP请求中自动添加一个名为“Authorization”的头部,它包含了从localStorage中获取的令牌。 在这里,我们还要考虑到token可能会过期,因此我们还可以添加一个拦截器检查HTTP响应。如果响应包含401状态码,我们会强制用户重新登录以获取新的token。代码如下: ```vue3 api.interceptors.response.use( response => response, error => { if (error.response.status === 401) { localStorage.removeItem('token'); router.push('/login'); } return Promise.reject(error); }); ``` 在这个拦截器中,我们首先检查响应是否包含401状态码。如果是,我们清除localStorage中的token并强制用户重新登录。 总之,Vue3中使用Axios拦截器为每个HTTP请求设置token是一种常见实践,并且可以非常轻松地实现。借助Axios拦截器,我们可以自动为每个HTTP请求设置token,并在token过期时强制用户重新登录。 ### 回答3: 在Vue3中使用Axios拦截器使用token进行身份验证是一种非常常见的做法。以下是详细的步骤: 第一步:安装Axios和Vue-Router 安装Axios和Vue-Router: ``` npm install axios vue-router --save ``` 该命令会将axios和vue-router安装到项目中。 第二步:创建Axios实例和拦截器 创建一个名为axios.js的新文件,并在其中添加以下代码: ```javascript import axios from "axios"; import router from "@/router"; const axiosInstance = axios.create({ baseURL: process.env.VUE_APP_API_BASE_URL }); axiosInstance.interceptors.request.use(config => { const token = localStorage.getItem("token"); if (token) { config.headers["Authorization"] = `Bearer ${token}`; } return config; }, error => { return Promise.reject(error); }); axiosInstance.interceptors.response.use(response => { return response; }, error => { if (error.response.status === 401) { router.push("/login"); } return Promise.reject(error); }); export default axiosInstance; ``` 在这里,我们创建了一个Axios实例,并在请求中添加了一个拦截器来检查本地存储中是否有token。如果存在,则将其添加到请求头中。此外,我们还添加了一个拦截器来处理401未授权错误响应,并重定向到登录页面。 第三步:在Vue组件中使用Axios实例 确保我们在请求数据时始终使用我们创建的Axios实例。为此,我们需要在组件中导入该实例: ```javascript import axiosInstance from "@/axios"; ``` 我们现在可以像这样在组件中使用Axios: ```javascript axiosInstance.get("/users") .then(response => { console.log(response); }) .catch(error => { console.log(error); }); ``` 现在,我们已经成功地设置了Axios拦截器使用token进行身份验证。我们可以在Axios实例中添加其他拦截器,以满足特定的需求。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值