Nuxt中服务端请求无法获取LocalStorage和Cookie的解决办法!

解决办法

在plugins中新建localStorage.js文件,内容如下:

import createPersistedState from 'vuex-persistedstate';
import * as Cookies from "js-cookie";

let cookieStorage = {
  getItem: function (key) {
    return Cookies.getJSON(key);
  },
  setItem: function (key, value) {
    let obj = {}
    if (value.loginState) {
      obj = {
        token: value.token,
        shopId: value.shopId,
        loginState: value.loginState
      }
    } else {
      obj = {
        token: '',
        shopId: '',
        loginState: false
      }
    }

    return Cookies.set(key, obj, {
      expires: 3,
      secure: false
    });
  },
  removeItem: function (key) {
    return Cookies.remove(key);
  }
};
export default (context) => {
  createPersistedState({
    storage: cookieStorage,
    getState: cookieStorage.getItem,
    setState: cookieStorage.setItem,
    removeState: cookieStorage.removeItem,
  })(context.store);

};

使用方法

在nuxt.config.js中设置

plugins: [
    { src: '~/plugins/localStorage.js', ssr: false }
],

定义好以上方法后,我们在获取到vuex数据的时候就会调用对应的getItem 和 setItem方法,将vuex的内容写入到cookie中。

那我们就可以通过在asyncData中 app 默认值中获取到cookie中写入的数据。

async asyncData({ app, route, context, store }) {
    let token = "";
    let shopId = "";

    if (
      app &&
      app.context &&
      app.context.req &&
      app.context.req.headers &&
      app.context.req.headers.cookie
    ) {
      let arrCookie = app.context.req.headers.cookie.split(";");
      let cookie = arrCookie.find(item => item.split("=")[0] === " vuex");
      if (cookie) {
        if (cookie.split("=")[1] != "") {
          let cookieData = JSON.parse(
            decodeURIComponent(cookie ? cookie.split("=")[1] : "")
          );
          token = cookieData.token;
          shopId = cookieData.shopId;
        }
      }
    }
}