1. 程式人生 > 實用技巧 >JavaSE之路-01

JavaSE之路-01

/**
 * setCookie
 *
 * @export
 * @param {string} name
 * @param {string} value
 * @param {number} [expireSeconds=600]
 */
function setCookie(name: string, value: string, expireSeconds = 600) {
    const exdate = new Date();
    exdate.setSeconds(exdate.getSeconds() + expireSeconds);
    document.cookie = `${name}=${escape(value)};expires=${exdate.toUTCString()}`;
}

/**
 * getCookie
 *
 * @export
 * @param {string} name
 * @returns
 */
function getCookie(name: string) {
    if (document.cookie.length > 0) {
        let cStart = document.cookie.indexOf(name + '=');
        if (cStart !== -1) {
            cStart = cStart + name.length + 1;
            let cEnd = document.cookie.indexOf(';', cStart);
            if (cEnd === -1) {
                cEnd = document.cookie.length;
            }
            return unescape(document.cookie.substring(cStart, cEnd));
        } else {
            return '';
        }
    }
    return '';
}

/**
 * clearCookie
 *
 * @export
 * @param {string} name
 */
function clearCookie(name: string) {
    setCookie(name, '');
}
// 設定
 setCookie(COOKIE_KEYS.LOGIN_AUTHORIZATION, res.access_token, res.expires_in);
                setCookie('username', params.username, res.expires_in);
獲取
${getCookie(COOKIE_KEYS.LOGIN_AUTHORIZATION)}
{getCookie(COOKIE_KEYS.USERNAME)}