After the vue front-end login gets the token, add it to the cookie, and use the token to get other data (add to the request header)

1. Log in to get the token and save it in the cookie

insert image description here

 Here my cookie is set to expire for one day
cookie.js code is as follows

// 设置cookie
export function setCookie(c_name, value, expiredays) {
  var exdate = new Date();
  exdate.setDate(exdate.getDate() + expiredays);
  document.cookie =
    c_name +
    '=' +
    encodeURIComponent(value) +
    ';expires=' +
    exdate.toGMTString() +
    ';path=/';
}
// 读取cookie
export function getCookie(c_name) {
  let c_start = null;
  let c_end = null;
  if (document.cookie.length > 0) {
    c_start = document.cookie.indexOf(c_name + '=');
    if (c_start != -1) {
      c_start = c_start + c_name.length + 1;
      c_end = document.cookie.indexOf(';', c_start);
      if (c_end == -1) c_end = document.cookie.length;
      return decodeURIComponent(document.cookie.substring(c_start, c_end));
    }
  }
  return '';
}
// 检查cookie
export function checkCookie(c_name) {
  let username = getCookie(c_name);
  console.log(username);
  if (username != null && username != '') {
    return true;
  } else {
    return false;
  }
}
// 清除cookie
export function clearCookie(name) {
  setCookie(name, '', -1);
}

main.js is imported into the global use

import { setCookie, getCookie, checkCookie, clearCookie } from '@/utils/cookie';
Vue.prototype.$setCookie = setCookie;
Vue.prototype.$getCookie = getCookie;
Vue.prototype.$checkCookie = checkCookie;
Vue.prototype.$clearCookie = clearCookie;

request.js request header add token

//导入
import {
    getCookie
} from '@/utils/cookie'
//使用
service.interceptors.request.use(
    res => {
        if (res) {
            if (getCookie("token")) {
                res.headers.Authorization = getCookie("token")
            }
            return res;
        }
    },
    err => {
        return Promise.reject(err);
    }
);

 Finally, the browser can view the

insert image description here

 And it can be seen in the request parameters when the next request is sentinsert image description here

Guess you like

Origin blog.csdn.net/w199809w/article/details/130226461