好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

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中,代码如下:

<template>
? <div class="login">
? ? <el-form
? ? ? :model="loginForm"
? ? ? :rules="fieldRules"
? ? ? ref="loginForm"
? ? ? label-position="left"
? ? ? label-width="0px"
? ? ? class="demo-ruleForm login-container"
? ? >
? ? ? <h2 class="title" style="padding-left: 22px">系统登录</h2>
? ? ? <el-form-item prop="account">
? ? ? ? <el-input
? ? ? ? ? type="text"
? ? ? ? ? v-model="loginForm.account"
? ? ? ? ? auto-complete="off"
? ? ? ? ? placeholder="账号"
? ? ? ? ></el-input>
? ? ? </el-form-item>
? ? ? <el-form-item prop="password">
? ? ? ? <el-input
? ? ? ? ? type="password"
? ? ? ? ? v-model="loginForm.password"
? ? ? ? ? auto-complete="off"
? ? ? ? ? placeholder="密码"
? ? ? ? ></el-input>
? ? ? </el-form-item>
? ? ? <el-form-item class="join_formitem">
? ? ? ? <el-form-item class="captcha">
? ? ? ? ? <el-col :span="12">
? ? ? ? ? ? <el-form-item prop="picLyanzhengma">
? ? ? ? ? ? ? <el-input
? ? ? ? ? ? ? ? type="text"
? ? ? ? ? ? ? ? placeholder="请输入验证码"
? ? ? ? ? ? ? ? class="yanzhengma_input"
? ? ? ? ? ? ? ? v-model="loginForm.picLyanzhengma"
? ? ? ? ? ? ? />
? ? ? ? ? ? </el-form-item>
? ? ? ? ? </el-col>
? ? ? ? ? <el-col class="line" :span="1">&nbsp;</el-col>
? ? ? ? ? <el-col :span="11">
? ? ? ? ? ? <input
? ? ? ? ? ? ? type="button"
? ? ? ? ? ? ? @click="createdCode"
? ? ? ? ? ? ? class="verification"
? ? ? ? ? ? ? v-model="checkCode"
? ? ? ? ? ? />
? ? ? ? ? </el-col>
? ? ? ? </el-form-item>
? ? ? </el-form-item>
? ? ? <el-form-item>?
? ? ? </el-form-item>
? ? ?
? ? ? <el-form-item style="width: 100%">
? ? ? ? <!-- <el-button type="primary" style="width:48%;" @click.native.prevent="reset">重 置</el-button> -->
? ? ? ? <el-button type="primary" style="width: 48%" @click="login()"
? ? ? ? ? >登 录</el-button
? ? ? ? >
? ? ? </el-form-item>
? ? </el-form>
? </div>
</template>

<script>
import { mapMutations } from "vuex";
import Cookies from "js-cookie";
export default {
? name: "login",
? components: {
? },
? data() {
? ? return {
? ? ? code: "",
? ? ? checkCode: "IHLE",
? ? ? data: "",
? ? ? loading: false,
? ? ? loginForm: {
? ? ? ? account: "admin",
? ? ? ? password: "123456",
? ? ? ? captcha: "",
? ? ? ? src: "",
? ? ? ? picLyanzhengma: "",
? ? ? },
? ? ? fieldRules: {
? ? ? ? account: [{ required: true, message: "请输入账号", trigger: "blur" }],
? ? ? ? password: [{ required: true, message: "请输入密码", trigger: "blur" }],
? ? ? ? picLyanzhengma: [
? ? ? ? ? { required: true, message: "请输入验证码", trigger: "blur" },
? ? ? ? ],
? ? ? },
? ? ? checked: false,
? ? };
? },
? methods: {
? ? ...mapMutations(["changeLogin"]),
? ? login() {
? ? ? this.loading = true;
? ? ? let _this = this;
? ? ? this.axios
? ? ? ? .post("/apis/admin/login/", { //调取后端登录接口
? ? ? ? ? username: this.loginForm.account,
? ? ? ? ? password: this.loginForm.password,
? ? ? ? })
? ? ? ? .then((res) => {
? ? ? ? ? console.log(res);
? ? ? ? ? console.log(res.data.data.token);
? ? ? ? ? _this.userToken = "Bearer " + res.data.data.token;
? ? ? ? ? // 将用户token保存到vuex中
? ? ? ? ? _this.changeLogin({ Authorization: _this.userToken });
? ? ? ? ? Cookies.set("Token", res.data.data.token); //登录成功后将token存储在cookie之中
? ? ? ? ? _this.$router.push("/questionnaire");
? ? ? ? });
? ? },
? ? reset() {
? ? ? this.$refs.loginForm.resetFields();
? ? },
? ? // 随机验证码
? ? createdCode() {
? ? ? // 先清空验证码输入
? ? ? this.code = "";
? ? ? this.checkCode = "";
? ? ? this.picLyanzhengma = "";
? ? ? // 验证码长度
? ? ? const codeLength = 4;
? ? ? // 随机数
? ? ? const random = new Array(
? ? ? ? 0,1,2,3,4,5,6,7,8,9,"A", "B","C","D", ?"E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z");
? ? ? for (let i = 0; i < codeLength; i++) {
? ? ? ? // 取得随机数的索引(0~35)
? ? ? ? let index = Math.floor(Math.random() * 36);
? ? ? ? // 根据索引取得随机数加到code上
? ? ? ? this.code += random[index];
? ? ? }
? ? ? // 把code值赋给验证码
? ? ? this.checkCode = this.code;
? ? },
? },
? mounted() {
? ? this.createdCode(), //创建验证码
? },
};
</script>

<style lang="scss" scoped>
.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;
}
</style>

调取后端登录接口成功,拿到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();
? ? ? ? }
? ? }
});

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

到此这篇关于vue请求接口并且携带token的实现的文章就介绍到这了,更多相关vue请求接口并且携带token内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

查看更多关于vue请求接口并且携带token的实现的详细内容...

  阅读:64次