Vue如何為GET或POST請求設(shè)置請求頭
為GET或POST請求設(shè)置請求頭
安裝vue-cookies
就通過我寫的一個小項目的登錄來講vue-cookies,登陸成功后拿到后臺返回的token值,把它保存到vue-cookies中
首先需要安裝vue-cookies
npm install vue-cookies --save
使用
import Vue from 'vue' import VueCookies from 'vue-cookies' Vue.use(VueCookies);
設(shè)置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("服務(wù)器異常");
?? ??? ??? ??? ??? ? })
?? ??? ??? ??? ?}
?? ??? ? }全局設(shè)置請求頭
//index.js
Vue.http.interceptors.push((request, next) => {
? ? //請求發(fā)送前的處理邏輯
? ? request.headers.set('auth', VueCookies.get("auth"))
? ? next((response) => {
? ? ? ? //請求發(fā)送后的處理邏輯
? ? ? ? //根據(jù)請求的狀態(tài),response參數(shù)返回給successCallback或errorCallback
? ? ? ? return response
? ? })
})vue項目設(shè)置請求頭權(quán)限問題
新建一個公共js文件。如: lp.js.
//設(shè)置請求消息頭
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: {
? ? ? ?// 獲取員工架構(gòu)
? ? ? 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;當(dāng)然在路由請求時需要設(shè)置,在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;以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
VUE v-for循環(huán)中每個item節(jié)點動態(tài)綁定不同函數(shù)的實例
今天小編就為大家分享一篇VUE v-for循環(huán)中每個item節(jié)點動態(tài)綁定不同函數(shù)的實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-09-09
vue.js移動端app之上拉加載以及下拉刷新實戰(zhàn)
這篇文章主要介紹了vue.js移動端app之上拉加載以及下拉刷新實戰(zhàn),非常具有實用價值,需要的朋友可以參考下2017-09-09
vue使用axios實現(xiàn)文件上傳進度的實時更新詳解
最近在學(xué)習(xí)axios,然后項目就用到了,所以這篇文章主要給大家介紹了關(guān)于vue中利用axios實現(xiàn)文件上傳進度的實時更新的相關(guān)資料,文中先對axios進行了簡單的介紹,方法大家理解學(xué)習(xí),需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧。2017-12-12
vue3中el-table實現(xiàn)多表頭并表格合并行或列代碼示例
這篇文章主要給大家介紹了關(guān)于vue3中el-table實現(xiàn)多表頭并表格合并行或列的相關(guān)資料,文中通過代碼介紹的非常詳細,對大家學(xué)習(xí)或者使用vue具有一定的參考借鑒價值,需要的朋友可以參考下2024-02-02

