您好,登錄后才能下訂單哦!
這篇文章主要介紹了Vue怎么為GET或POST請求設置請求頭的相關知識,內容詳細易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇Vue怎么為GET或POST請求設置請求頭文章都會有所收獲,下面我們一起來看看吧。
就通過我寫的一個小項目的登錄來講vue-cookies,登陸成功后拿到后臺返回的token值,把它保存到vue-cookies中
首先需要安裝vue-cookies
npm install vue-cookies --save
使用
import Vue from 'vue' import VueCookies from 'vue-cookies' Vue.use(VueCookies);
設置cookies
this.$cookies.set("自定義名字",后臺獲取的token)
示例
//Login.vue Login(){ //登錄 this.$http.post('home/login', {"uPwd":this.password,"uPhone":this.account}).then(result=>{ if(result.body.status===200){ this.$cookies.set("auth",result.body.data); let redirect=decodeURIComponent(this.$route.query.redirect||"/home"); this.$router.push({path:redirect}); }else{ Toast('輸入密碼或賬號錯誤,請重新輸入'); } }).catch(function(){ console.log("服務器異常"); }) } }
全局設置請求頭
//index.js Vue.http.interceptors.push((request, next) => { //請求發送前的處理邏輯 request.headers.set('auth', VueCookies.get("auth")) next((response) => { //請求發送后的處理邏輯 //根據請求的狀態,response參數返回給successCallback或errorCallback return response }) })
新建一個公共js文件。如: lp.js.
//設置請求消息頭 export function headers(contentType,token){ let headers={}; headers['Content-Type'] = contentType ? contentType : 'application/json;charset=utf-8'; let a = window.location.href; let b = a.indexOf("#"); let loginUrl = a.substring(b+2); if(loginUrl){ localStorage.loginUrl = loginUrl; } let url = a.substring(0,b+2); if(loginUrl==='login' || loginUrl==='reg' || loginUrl==='phoneAuth' || loginUrl=='emailInfo'){ token=''; }else{ token=window.localStorage.getItem('jingjing_login_token'); } token = token ? token : ''; let key = 'jmjbGEWO4EyItpA4'; let current_timestamp = new Date().getTime() + ''; let nonce_str = getNonceStr(32); let lp_sign = sign(token, current_timestamp, nonce_str, key); headers['token'] = token; headers['current-timestamp'] = current_timestamp; headers['nonce-str'] = nonce_str; headers['lp-sign'] = lp_sign; return headers;
} //生成隨機字符串 export function getNonceStr(len) { len = len || 32; let chars = '1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; let maxPos = chars.length; let s = ''; for (let i = 0; i < len; i++) { s += chars.charAt(Math.floor(Math.random() * maxPos)); } return s; } // 在組件中使用直接引用, import {headers} from '@/assets/js/common/lp.js' methods: { // 獲取員工架構 getTree() { // that.$emit('updataTree') let that = this this.$http({ method:"get", url:api.treeList, **headers:headers('application/json;charset=utf-8'),** cache:false }).then(function(res){ if(res.data.code==10000 || res.data.data==null){ that.treeDatas = res.data.data console.log(that.treeDatas,'<//====treeDatas') }else{ that.$message.error(res.data.msg); } }); }, }
其中api.js中這么定義
let Butterfly="http://192.168.6.207:8891/jersey/";//xxip const api = { baseUrl:Butterfly, treeList:Butterfly+'enterpriseInfo/current/user', }; export default api;
當然在路由請求時需要設置,在router.js文件中
router.beforeEach((to, from, next) => { if(!localStorage.jingjing_login_token && to.path!=='/' && to.name !== 'phoneAuth' && to.name !== 'reg' && to.name !== 'agree' && to.name !== 'restPsd' && to.name !== 'ablityAssessment' && to.name !== 'leaveAssessment' && to.name !== 'contact' && to.name !== 'wasAsked' && to.name !== 'newWitesite_index' && to.name !== 'bySinging' && to.name !== 'brokenQuery' && to.name !== 'login'){ router.push({path:'/login'}); }else{ let a = window.location.href; let b = a.indexOf("#"); let loginUrl = a.substring(b+2); if(loginUrl){ localStorage.loginUrl = loginUrl; } next(); } }); export default router;
關于“Vue怎么為GET或POST請求設置請求頭”這篇文章的內容就介紹到這里,感謝各位的閱讀!相信大家對“Vue怎么為GET或POST請求設置請求頭”知識都有一定的了解,大家如果還想學習更多知識,歡迎關注億速云行業資訊頻道。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。