截取地址栏search部分
function getSearch (){
const obj = {}
const searchStr = location.search
if(typeof searchStr === "string"){
const searchIndex = searchStr.indexOf("?")
const searchKeyValue = searchStr.slice(searchIndex + 1).split("&")
for (let i = 0 ;i<searchKeyValue.length;i++){
const key = searchKeyValue[i].split("=")[0]
const value = searchKeValue[i]split("=")[1]
obj[key] = decodeURIComponent(value)//进行编码
}
}
return obj
}
调用后端接口,成功后,后端将token,设置到cookie中,在跨域的环境中是获取不到cookie的,所以,在本地开发中要写死token;在测试和生产环境中没有跨域问题,可以正常获取;
获取cookie的方法:
document.cookie
function sliceToken(){
const obj = {}
const searchKeyValue = document.cookie.split(";")
for (let i = 0 ;i<searchKeyValue.length;i++){
const key = searchKeyValue[i].split("=")[0].trim()//要去除空格
const value = searchKeValue[i]split("=")[1].trim()
obj[key] = value
}
return obj
}
从获取的数据中将cookie截取出来。放在请求头部
const Url = computed(()=>{
let str = encodeURIComponent(`oaUserInfo=${JSON.stringify(userStore.userInfo)}`)
return `http://***.***.*.***:****/#/index?${str}`
})
let str = location.hash.split('?')[1]
let info = str.split('&')
let obj = {}
info.forEach(item=>{
const key = item.split("=")[0]
const value = item.split("=")[1]
if(key==='UserName'){
obj[key] = decodeURIComponent(value)//进行编码
}else{
obj[key] = value
}
})
console.log(obj,'obj')
//
if (location.hash.includes('UserInfo')) {
let str = decodeURIComponent(location.hash.split('?')[1])
let info = JSON.parse(str.split('=')[1])
console.log(info, 'info')
localStorage.setItem("token", info.userToken)
}
获取地址栏参数,返回一个对象
const getURLParameters = url =>
(url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce(
(a, v) => ((a[v.slice(0, v.indexOf('='))] = v.slice(v.indexOf('=') + 1)), a),
{}
);
// 事例
getURLParameters('http://url.com/page?n=Adam&s=Smith'); // {n: 'Adam', s: 'Smith'}
getURLParameters('google.com'); // {}