vue请求接口并且携带token代码实现方法

作者:袖梨 2022-07-27

本篇文章小编给大家分享一下vue请求接口并且携带token代码实现方法,文章代码介绍的很详细,小编觉得挺不错的,现在分享给大家供大家参考,有需要的小伙伴们可以来看看。

一、处理跨域问题

1.在vue2.0的config文件夹下面的index.js文件里面或者在vue3.0中新建vue.config.js文件,写入以下代码:

module.exports = {
    devServer: {
        open: true,
        port: 8080,
        //以上的ip和端口是我们本机的;下面为需要跨域的
        proxy: { //配置跨域
            '/apis': {
                target: 'http://47.98.143.163:8000/', //这里后台的地址模拟的;应该填写你们真实的后台接口
                ws: true,
                changOrigin: true, //允许跨域
                pathRewrite: {
                    '^/apis': '' //请求的时候使用这个api就可以
                }
            }
        }
    },
}

在需要调取接口的方法中通过/apis加上接口来拿取数据,示例如下:

    //编辑问卷列表
    edit(id) {
      this.axios
        .put("/apis/zhmq/wj/wj/" + id + "/", {
          title: this.inputtitle,
          explain: this.titletextarea,
        })
        .then((res) => {
          console.log(121324654);
          this.centerDialogVisible = false;
          this.getarr();
        })

        .catch((e) => fn);
    }

二、登录获取token

在调取后端接口时,需要给后端传一个token过去,才可以拿到后端的数据,但是后端没有给我登录接口,让我使用另一个项目登录时的token,结果就是写着写着突然没数据了。。。。,当时写的代码是这样的:

return:{
token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwic2Vzc2lvbl9pZCI6Ijg0MmRlNGQ0LTVkODktNDg0ZC1hMDk1LWMzNTdkNmJmNDRjMSIsImV4cCI6MTYyOTQyNTI4Mywib3JpZ19pYXQiOjE2MjkzMzg4ODN9.AeO5kKdojnF3kjnIfmuShMyEvOvVLavkc4gcUnH9giU"
}
getlist(){
this.axios
        .get("/apis/zhmq/wj/wj/display/" + this.titleId + "/", {
        //添加请求头
           headers: {
             Authorization: "Bearer " + this.token,
           },
        })
        .then((res) => {
          console.log(res);
        })
        .catch((e) => fn);
   }

导致的结果就是我每调一个接口,就需要把headers复制粘贴一遍,而且token还很快就会过期,实在是难受,就和后端商量让他给我一个登录接口,不然实在是麻烦。。。

三、开发登录页面存储token

首先编写登录页面,同时拿取token,把token存储到vuex中,代码如下:





调取后端登录接口成功,拿到token同时存放到vuex中

在store文件夹下面的index.js文件中,写入以下代码,将token存储到localStorage中:

import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const store = new Vuex.Store({
    state: {
        // 存储token
        Authorization: localStorage.getItem('Authorization') ?localStorage.getItem('Authorization') : ''
    },

    mutations: {
        // 修改token,并将token存入localStorage
        changeLogin(state, user) {
            state.Authorization = user.Authorization;
            localStorage.setItem('Authorization', user.Authorization);
        }
    }
});
export default store;

3.因为请求后端接口需要携带token放到请求头headers中,因而在main.js文件中,写入以下代码:

//引入axios
import axios from 'axios'
//使用axios
Vue.prototype.axios = axios
    //axios携带token
    // 添加请求拦截器,在请求头中加token
axios.interceptors.request.use(
    config => {
        if (localStorage.getItem('Authorization')) {
            config.headers.Authorization = localStorage.getItem('Authorization');
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    });

即可在请求接口的时候,可以携带token拿取后端数据,因而调取后端接口就可以省略请求头的添加:

  //编辑问卷列表
    edit(id) {
      this.axios
        .put("/apis/zhmq/wj/wj/" + id + "/", {
          title: this.inputtitle,
          explain: this.titletextarea,
        })
        .then((res) => {
          console.log(121324654);
          this.centerDialogVisible = false;
          this.getarr();
        })
        .catch((e) => fn);
    }

四、通过token进行路由的拦截

在main.js后者router文件夹下面的index.js文件里面加入以下代码,进行全局前置路由守卫,代码如下:

router.beforeEach((to, from, next) => {

    if (to.path == '/login' || to.path == '/register') {
        next();
    } else {
        const token = localStorage.getItem('Authorization'); // 获取token
        // token不存在
        if (token === null || token === '') {
            alert('您还没有登录,请先登录');
            next('/login');
        } else {
            next();
        }
    }
});

完成登录路由拦截以及请求携带请求头

相关文章

精彩推荐