您好,登錄后才能下訂單哦!
這篇文章主要介紹“vue請求接口并攜帶token如何實現”,在日常操作中,相信很多人在vue請求接口并攜帶token如何實現問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”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,結果就是寫著寫著突然沒數據了。。。。,當時寫的代碼是這樣的:
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存儲到vuex中,代碼如下:
<template> <div class="login"> <el-form :model="loginForm" :rules="fieldRules" ref="loginForm" label-position="left" label-width="0px" class="demo-ruleForm login-container" > <h3 class="title" >系統登錄</h3> <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 > <!-- <el-button type="primary" @click.native.prevent="reset">重 置</el-button> --> <el-button type="primary" @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); }
在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如何實現”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。