Vue如何为GET或POST请求设置请求头
更新时间:2022年04月08日 15:13:52 作者:阳光之末亚
这篇文章主要介绍了Vue如何为GET或POST请求设置请求头,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
为GET或POST请求设置请求头
安装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);
设置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
})
})vue项目设置请求头权限问题
新建一个公共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-router 2.0 常用基础知识点之router-link
这篇文章主要介绍了详解vue-router 2.0 常用基础知识点之router-link,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2017-05-05
vue draggable resizable gorkys与v-chart使用与总结
这篇文章主要介绍了vue draggable resizable gorkys与v-chart使用与总结,本文给大家介绍的非常详细,具有一定的参考借鉴价值,需要的朋友可以参考下2019-09-09
Fragment 占位组件不生成标签与路由组件lazyLoad案例
这篇文章主要为大家介绍了Fragment 占位组件不生成标签与路由组件lazyLoad案例详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2022-10-10
Vue+Openlayer中使用select选择要素的实现代码
本文通过实例代码给大家介绍Vue+Openlayer中使用select选择要素,代码简单易懂,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧2021-08-08
vue3项目vite.config.js配置代理、端口、打包名以及图片压缩
这篇文章主要给大家介绍了关于vue3项目vite.config.js配置代理、端口、打包名以及图片压缩的相关资料,因为3.0版本中vue已经内置了很多关于webpack的配置,一般情况下开箱即用,需要修改则可以在vue.config.js文件中完成,需要的朋友可以参考下2023-12-12


最新评论