公共數據集采集-axios獲取cookie中的session值


1

/*獲取指定名稱的cookie值*/ 
export function getCookieValue(name) {
  let result = document.cookie.match(
    "(^|[^;]+)\\s*" + name + "\\s*=\\s*([^;]+)"
  );
  return result ? result.pop() : "";
}

2

 const session = getCookieValue("session");
            console.log('session',session);

3如果需要前端把session存入cookie,我這里是后端直接存入

session

// 添加請求攔截器
service.interceptors.request.use(
  config => {
    console.log(config.headers)
    return config;
  },
  err => {
    console.log(err);
  }
);
service.interceptors.response.use(
  response => {
    console.log(window.location.hash)
    const hash = window.location.hash
    if (response.data.code === 8101 && hash !== '#/') {
      router.replace({ path: "/" });
      Message({
        message: "登陸過期",
        type: "warning"
      });
    }
    let res = {};
    res.status = response.status;
    res.data = response.data;
    return res;
  },
  err => console.log(err)
);

token

后台除了登錄接口之外,都需要token權限驗證,我們可以通過添加axios請求攔截器來添加token,以保證擁有獲取數據的權限

在main.js中添加代碼,在將axios掛載到vue原型之前添加下面的代碼

\```

//請求在到達服務器之前,先會調用use中的這個回調函數來添加請求頭信息

axios.interceptors.request.use(config=>{

//為請求頭對象,添加token驗證的Authorization字段

config.headers.Authorization = window.sessionStorage.getItem("token")

return config

})

4掛載路由導航守衛

ps:可以在跳轉前執行操作
import { Dialog } from 'element-ui';
根據session:

 // 驗證session
      router.beforeEach((to, from, next) => {
        const session = getCookieValue("session");
        if (!session && to.name !== 'login') {
          window.alert("登錄已過期!")
          
          next({ name: 'login' }) 
        } else {
          next()
        }
      })

根據token

router.beforeEach((to,from,next)=>{

if(to.path === '/login')

return next();

//獲取token

const tokenStr = window.sessionStorage.getItem('token');

if(!tokenStr)

return next('/login');

next();

})

export default router


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM