最近项目中将原来的session认证迁移到token,原有的web界面的Ajax请求均没有携带头部鉴权参数,一个一个改太浪费时间,可以在请求开始前增加头部的鉴权字段
setToken()
/**
* 初始化之后获取token保存
*/
function setToken () {
var token = getCookie('access_token')
if (token && token !== null && token !== undefined) {
localStorage.setItem('access_token', token)
console.log('init save token.......')
//添加全局请求头
addGlobalHeader()
} else {
console.log('cookie has no token.......')
}
}
/**
* 获取Cookies
* [getCookie description]
* @param {[type]} name [description]
* @return {[type]} [description]
*/
function getCookie(name){
var strcookie = document.cookie;//获取cookie字符串
var arrcookie = strcookie.split("; ");//分割
//遍历匹配
for ( var i = 0; i < arrcookie.length; i++) {
var arr = arrcookie[i].split("=");
if (arr[0] == name){
return arr[1];
}
}
return "";
}
/**
* 添加全局的请求头
* [addGlobalHeader description]
*/
function addGlobalHeader() {
let token = localStorage.getItem('access_token')
if (token && token !== undefined && token !== 'null') {
$.ajaxSetup({
beforeSend: function(request) {
request.setRequestHeader("Authorization", 'Bearer ' + token);
}
})
}
}
网友评论