vue3中axios怎么添加响应头存储token值分权跳转鉴权
在Vue3中使用axios发送请求,并添加响应头、存储token值、实现分权跳转和鉴权,可以按照以下步骤进行操作:
- 安装
axios和vue-router:在项目根目录下运行以下命令安装依赖:
npm install axios vue-router
- 创建一个
axios实例并设置默认的请求头: 在项目的src目录下创建一个api文件夹,并在该文件夹下创建一个http.js文件,用于创建axios实例。
// src/api/http.js
import axios from 'axios';
const http = axios.create({
baseURL: 'http://your-api-url.com', // 设置请求的基础URL
timeout: 5000 // 设置请求超时时间
});
http.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('token'); // 设置默认请求头,存储token值
export default http;
- 使用
axios发送请求: 在需要发送请求的组件中,引入http.js文件,并使用http实例发送请求。
// src/views/Example.vue
<template>
<div>
<button @click="getData">发送请求</button>
</div>
</template>
<script>
import http from '@/api/http';
export default {
methods: {
getData() {
http.get('/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
});
}
}
};
</script>
- 实现分权跳转和鉴权: 在需要进行分权跳转和鉴权的路由配置文件中,对需要进行鉴权的路由进行配置。
// src/router/index.js
import { createRouter, createWebHashHistory } from 'vue-router';
const routes = [
{
path: '/home',
name: 'Home',
component: () => import('@/views/Home.vue')
},
{
path: '/admin',
name: 'Admin',
component: () => import('@/views/Admin.vue'),
meta: { requiresAuth: true } // 设置需要鉴权的路由
}
];
const router = createRouter({
history: createWebHashHistory(),
routes
});
router.beforeEach((to, from, next) => {
const token = localStorage.getItem('token');
if (to.meta.requiresAuth && !token) {
// 需要鉴权的路由且未登录,跳转到登录页面
next('/login');
} else if (!to.meta.requiresAuth && token) {
// 不需要鉴权的路由且已登录,跳转到首页
next('/home');
} else {
next();
}
});
export default router;
这样就完成了在Vue3中使用axios发送请求,并添加响应头、存储token值、实现分权跳转和鉴权的操作。需要注意的是,以上代码仅为示例,具体的业务逻辑可能需要根据实际情况进行调整
原文地址: https://www.cveoy.top/t/topic/h4cx 著作权归作者所有。请勿转载和采集!