赞
踩
前端请求携带tokenId,来让后端知道自己是谁,以及自己的登陆状态是否过期。在axios中添加拦截器,实现每个请求都自动额外添加tokenId参数。
在src目录下添加一个目录——service,里面新建文件——index.js,在这当中填入代码:
- import axios from 'axios';
- import router from '../router/index';
-
- // `timeout` 指定请求超时的毫秒数(0 表示无超时时间)
- // 如果请求超过 `timeout` 的时间,请求将被中断
- const service = axios.create({
- timeout: 10000
- })
-
- service.interceptors.request.use(config => {
- //在这里可以打印axios的请求参数。可以看到post当中的参数是data
- console.log(config);
- if (localStorage.getItem("tokenId") != null) {
- config.data['tokenId'] = localStorage.getItem('tokenId');
- } else {
- router.push("/main");
- }
- return config;
- }, error => {
- Promise.reject(error);
- });
-
- export default service;

在main.js文件中就不用引入axios了,引入这个文件即可,类似于引入公共文件一样:
- import axios from './service/index';
-
- Vue.prototype.$axios = axios;
这样在组件vue文件中,便可以直接使用this.$axios发起网络请求了:
- this.$axios
- .post("http://localhost:3000/order", {
- //本来每个请求需要撸入这行代码,有了拦截器,可以删掉这行代码了
- // tokenId: localStorage.getItem("tokenId"),
- orders: "all"
- })
- .then(body => {
- this.orders = body.data.orders;
- })
- .catch(error => {
- console.log(error);
- });
过两天更新一下,更新一下response拦截器,实现的功能是当后端的redis发现tokenId过期时候,使页面返回到首页,注销掉登陆的信息,以期客户重新登陆。
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。