cookie的知识点
问题:单点登录发现,存储于cookie中的token值,在主域相同,子域不同(例如aaa.xxx.com和bbb.xxx.com)的两个域中,会互相影响
问题原因:
(1)cookie的作用域是domain本身以及domain下的所有子域名
(2)cookie基础知识点
JS操作cookie的增删改查
(1)查询
/** * 获取cookie * * @export * @param {string} name * @returns */ export function getCookie(name) { const strcookie = document.cookie // 获取cookie字符串 const arrcookie = strcookie.split('; ') // 分割 // 遍历匹配 // tslint:disable-next-line: prefer-for-of for (let i = 0; i < arrcookie.length; i++) { const arr = arrcookie[i].split('=') if (arr[0] === name) { return arr[1] } } return '' }
(2)增、改方法相同
/** * 设置cookie * * @export * @param {string} name * @param {string} value * @param {number} day * @param {string} [path='/'] */ export function setCookie( name, value, day, path = '/' ) { const d = new Date() d.setTime(d.getTime() + 24 * 60 * 60 * 1000 * day) window.document.cookie = name + '=' + value + ';path=' + path + ';expires=' + d.toUTCString() }
(3)删除
/** * 删除cookie 使cookie过期 * * @export * @param {string} name * @param {string} [path='/'] */ export function deleteCookie(name, path = '/') { const value = getCookie(name) if (value !== null) { const d = new Date() d.setTime(d.getTime() - 1) window.document.cookie = name + '=' + value + ';path=' + path + ';expires=' + d.toUTCString() } }