1. 程式人生 > >nuxt獲取前端cookie

nuxt獲取前端cookie

使用nuxt框架做http請求,每次要把cookie傳到後端,使用document.cookies不能在後端獲取cookies,使用cookie-universal-nuxt外掛

https://www.npmjs.com/package/cookie-universal-nuxt

安裝:

npm i --save cookie-universal-nuxt

在nuxt.config.js中使用

{
  modules: [
    // Simple usage
    'cookie-universal-nuxt',
 
    // With options
    ['cookie-universal-nuxt', { alias: 'cookiz' }],
 ]
}

使用@nuxtjs/proxy和@nuxtjs/axios外掛下的axios請求時在頭部帶上cookie

只需新增config.headers.Authorization = app.$cookies.get('token')

plugins/axios.js:

import qs from "qs";

export default function ({ $axios, app }) {
  // console.log(app.$cookies.get('token'))  //每次請求獲取cooie
  $axios.onRequest(config => {
    //獲取cookie放在頭部傳到後端
    config.headers.Authorization = app.$cookies.get('token')
    config.data = qs.stringify(config.data, {
      allowDots: true //Option allowDots can be used to enable dot notation
    });
    return config;
  });

  $axios.onResponse(response => {
    return Promise.resolve(response.data);
  });

  $axios.onError(error => {
    return Promise.reject(error);
  });
}