vue请求接口并且携带token的实现

目录

  • 一、处理跨域问题
  • 二、登录获取token
  • 三、开发登录页面存储token
  • 四、通过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 【vue请求接口并且携带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中,代码如下:
.login {display: flex; justify-content: center; align-items: center; height: 100%; // height: 600px; background-image: url("../../assets/login-background.jpg"); background-size: cover; }.login-container {-webkit-border-radius: 5px; border-radius: 5px; -moz-border-radius: 5px; background-clip: padding-box; margin: 100px auto; width: 350px; padding: 35px 35px 15px 35px; background: #fff; border: 1px solid #eaeaea; box-shadow: 0 0 25px #cac6c6; .title {margin: 0px auto 30px auto; text-align: center; color: #505458; }.remember {margin: 0px 0px 35px 0px; }}.yanzhengma_input {font-family: "Exo 2", sans-serif; // border: 1px solid #fff; // color: #fff; outline: none; // border-radius: 12px; letter-spacing: 1px; font-size: 17px; font-weight: normal; // background-color: rgba(82,56,76,.15); padding: 5px 0 5px 10px; // margin-left: 30px; height: 30px; margin-top: 30px; // border: 1px solid #e6e6e6; }.verification {background: white; margin-top: 35px; border-radius: 12px; width: 100px; letter-spacing: 5px; margin-left: 50px; height: 40px; transform: translate(-15px, 0); }.captcha {height: 50px; text-align: justify; }

调取后端登录接口成功,拿到token同时存放到vuex中
在store文件夹下面的index.js文件中,写入以下代码,将token存储到localStorage中:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({state: {// 存储tokenAuthorization: localStorage.getItem('Authorization') ?localStorage.getItem('Authorization') : ''},mutations: {// 修改token,并将token存入localStoragechangeLogin(state, user) {state.Authorization = user.Authorization; localStorage.setItem('Authorization', user.Authorization); }}}); export default store;

3.因为请求后端接口需要携带token放到请求头headers中,因而在main.js文件中,写入以下代码:
//引入axiosimport axios from 'axios'//使用axiosVue.prototype.axios = axios//axios携带token// 添加请求拦截器,在请求头中加tokenaxios.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(); }}});

完成登录路由拦截以及请求携带请求头
到此这篇关于vue请求接口并且携带token的实现的文章就介绍到这了,更多相关vue请求接口并且携带token内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

    推荐阅读