vue請(qǐng)求接口并且攜帶token的實(shí)現(xiàn)
一、處理跨域問(wèn)題
1.在vue2.0的config文件夾下面的index.js文件里面或者在vue3.0中新建vue.config.js文件,寫入以下代碼:
module.exports = { devServer: { open: true, port: 8080, //以上的ip和端口是我們本機(jī)的;下面為需要跨域的 proxy: { //配置跨域 '/apis': { target: 'http://47.98.143.163:8000/', //這里后臺(tái)的地址模擬的;應(yīng)該填寫你們真實(shí)的后臺(tái)接口 ws: true, changOrigin: true, //允許跨域 pathRewrite: { '^/apis': '' //請(qǐng)求的時(shí)候使用這個(gè)api就可以 } } } }, }
在需要調(diào)取接口的方法中通過(guò)/apis加上接口來(lái)拿取數(shù)據(jù),示例如下:
? ? //編輯問(wèn)卷列表 ? ? 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
在調(diào)取后端接口時(shí),需要給后端傳一個(gè)token過(guò)去,才可以拿到后端的數(shù)據(jù),但是后端沒(méi)有給我登錄接口,讓我使用另一個(gè)項(xiàng)目登錄時(shí)的token,結(jié)果就是寫著寫著突然沒(méi)數(shù)據(jù)了。。。。,當(dāng)時(shí)寫的代碼是這樣的:
return:{ token: "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2lkIjoxLCJ1c2VybmFtZSI6ImFkbWluIiwic2Vzc2lvbl9pZCI6Ijg0MmRlNGQ0LTVkODktNDg0ZC1hMDk1LWMzNTdkNmJmNDRjMSIsImV4cCI6MTYyOTQyNTI4Mywib3JpZ19pYXQiOjE2MjkzMzg4ODN9.AeO5kKdojnF3kjnIfmuShMyEvOvVLavkc4gcUnH9giU" } getlist(){ this.axios .get("/apis/zhmq/wj/wj/display/" + this.titleId + "/", { //添加請(qǐng)求頭 headers: { Authorization: "Bearer " + this.token, }, }) .then((res) => { console.log(res); }) .catch((e) => fn); }
導(dǎo)致的結(jié)果就是我每調(diào)一個(gè)接口,就需要把headers復(fù)制粘貼一遍,而且token還很快就會(huì)過(guò)期,實(shí)在是難受,就和后端商量讓他給我一個(gè)登錄接口,不然實(shí)在是麻煩。。。
三、開(kāi)發(fā)登錄頁(yè)面存儲(chǔ)token
首先編寫登錄頁(yè)面,同時(shí)拿取token,把token存儲(chǔ)到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">系統(tǒng)登錄</h2> ? ? ? <el-form-item prop="account"> ? ? ? ? <el-input ? ? ? ? ? type="text" ? ? ? ? ? v-model="loginForm.account" ? ? ? ? ? auto-complete="off" ? ? ? ? ? placeholder="賬號(hào)" ? ? ? ? ></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="請(qǐng)輸入驗(yàn)證碼" ? ? ? ? ? ? ? ? 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: "請(qǐng)輸入賬號(hào)", trigger: "blur" }], ? ? ? ? password: [{ required: true, message: "請(qǐng)輸入密碼", trigger: "blur" }], ? ? ? ? picLyanzhengma: [ ? ? ? ? ? { required: true, message: "請(qǐng)輸入驗(yàn)證碼", trigger: "blur" }, ? ? ? ? ], ? ? ? }, ? ? ? checked: false, ? ? }; ? }, ? methods: { ? ? ...mapMutations(["changeLogin"]), ? ? login() { ? ? ? this.loading = true; ? ? ? let _this = this; ? ? ? this.axios ? ? ? ? .post("/apis/admin/login/", { //調(diào)取后端登錄接口 ? ? ? ? ? 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存儲(chǔ)在cookie之中 ? ? ? ? ? _this.$router.push("/questionnaire"); ? ? ? ? }); ? ? }, ? ? reset() { ? ? ? this.$refs.loginForm.resetFields(); ? ? }, ? ? // 隨機(jī)驗(yàn)證碼 ? ? createdCode() { ? ? ? // 先清空驗(yàn)證碼輸入 ? ? ? this.code = ""; ? ? ? this.checkCode = ""; ? ? ? this.picLyanzhengma = ""; ? ? ? // 驗(yàn)證碼長(zhǎng)度 ? ? ? const codeLength = 4; ? ? ? // 隨機(jī)數(shù) ? ? ? 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++) { ? ? ? ? // 取得隨機(jī)數(shù)的索引(0~35) ? ? ? ? let index = Math.floor(Math.random() * 36); ? ? ? ? // 根據(jù)索引取得隨機(jī)數(shù)加到code上 ? ? ? ? this.code += random[index]; ? ? ? } ? ? ? // 把code值賦給驗(yàn)證碼 ? ? ? this.checkCode = this.code; ? ? }, ? }, ? mounted() { ? ? this.createdCode(), //創(chuàng)建驗(yàn)證碼 ? }, }; </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>
調(diào)取后端登錄接口成功,拿到token同時(shí)存放到vuex中
在store文件夾下面的index.js文件中,寫入以下代碼,將token存儲(chǔ)到localStorage中:
import Vue from 'vue'; import Vuex from 'vuex'; Vue.use(Vuex); const store = new Vuex.Store({ ? ? state: { ? ? ? ? // 存儲(chǔ)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.因?yàn)檎?qǐng)求后端接口需要攜帶token放到請(qǐng)求頭headers中,因而在main.js文件中,寫入以下代碼:
//引入axios import axios from 'axios' //使用axios Vue.prototype.axios = axios //axios攜帶token // 添加請(qǐng)求攔截器,在請(qǐng)求頭中加token axios.interceptors.request.use( config => { if (localStorage.getItem('Authorization')) { config.headers.Authorization = localStorage.getItem('Authorization'); } return config; }, error => { return Promise.reject(error); });
即可在請(qǐng)求接口的時(shí)候,可以攜帶token拿取后端數(shù)據(jù),因而調(diào)取后端接口就可以省略請(qǐng)求頭的添加:
//編輯問(wèn)卷列表 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); }
四、通過(guò)token進(jìn)行路由的攔截
在main.js后者router文件夾下面的index.js文件里面加入以下代碼,進(jìn)行全局前置路由守衛(wèi),代碼如下:
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('您還沒(méi)有登錄,請(qǐng)先登錄'); ? ? ? ? ? ? next('/login'); ? ? ? ? } else { ? ? ? ? ? ? next(); ? ? ? ? } ? ? } });
完成登錄路由攔截以及請(qǐng)求攜帶請(qǐng)求頭
到此這篇關(guān)于vue請(qǐng)求接口并且攜帶token的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)vue請(qǐng)求接口并且攜帶token內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
使用vue-cli+webpack搭建vue開(kāi)發(fā)環(huán)境的方法
這篇文章主要介紹了使用vue-cli+webpack搭建vue開(kāi)發(fā)環(huán)境的方法,需要的朋友可以參考下2017-12-12vue實(shí)現(xiàn)彈窗引用另一個(gè)頁(yè)面窗口
這篇文章主要介紹了vue實(shí)現(xiàn)彈窗引用另一個(gè)頁(yè)面窗口,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-04-04Vue組件化(ref,props,?mixin,.插件)詳解
這篇文章主要介紹了Vue組件化(ref,?props,?mixin,?插件)的相關(guān)知識(shí),包括ref屬性,props配置項(xiàng)及mixin混入的方式,本文通過(guò)示例代碼多種方式相結(jié)合給大家介紹的非常詳細(xì),需要的朋友可以參考下2022-05-05vue項(xiàng)目實(shí)現(xiàn)設(shè)置根據(jù)路由高亮對(duì)應(yīng)的菜單項(xiàng)操作
這篇文章主要介紹了vue項(xiàng)目實(shí)現(xiàn)設(shè)置根據(jù)路由高亮對(duì)應(yīng)的菜單項(xiàng)操作,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2020-08-08vue+element-ui JYAdmin后臺(tái)管理系統(tǒng)模板解析
這篇文章主要介紹了vue+element-ui JYAdmin后臺(tái)管理系統(tǒng)模板解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-07-07詳解Vue3.0 前的 TypeScript 最佳入門實(shí)踐
這篇文章主要介紹了詳解Vue3.0 前的 TypeScript 最佳入門實(shí)踐,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-06-06django+vue項(xiàng)目搭建實(shí)現(xiàn)前后端通信
本文主要介紹了django+vue項(xiàng)目搭建實(shí)現(xiàn)前后端通信,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-02-02