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"> </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內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!