使用nuxtServerInit时缓存的访问令牌

Vue.js

小小

2020-03-24

使用Nuxt时,我遇到了与授权(JWT)有关的缓存问题。

这是在nuxtServerInit其中设置访问令牌的操作:

// store/index.js

import cookie from 'cookie';

export const state = () => ({
  authCookie: 'MyAuthCookie',
});

export const actions = {
  async nuxtServerInit({ dispatch, commit, state }, { req }) {
    // Check for access token
    const accessToken = req.headers.cookie &&
      cookie.parse(req.headers.cookie)[state.authCookie];

    // Set the access token, if there is one
    if (accessToken) {
      commit('auth/setAccessToken', accessToken);
    }
  },
};

accessToken状态随后用于设置Authorization此插件中所有将来请求标头:

// plugins/axios.js

export default function ({ app, store }) {
  app.$axios.onRequest((config) => {
    // Set the `Authorization` header for future requests if we're logged in
    if (store.getters['auth/isLoggedIn']) {
      config.headers.common.Authorization = `Bearer ${store.state.auth.accessToken}`;
    }
  });
};

Nuxt将客户端和服务器之间共享的数据存储在内window.__NUXT__<script>标签中的全局变量中,并且由于我正在积极地缓存相关页面(使用Akamai),因此访问令牌将永远不会更新。

是否有更好的方法来处理此问题并防止访问令牌被缓存?或者换句话说,如何防止将accessToken状态写入全局__NUXT__变量?

第3485篇《使用nuxtServerInit时缓存的访问令牌》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

1个回答
小哥小哥 2020.03.24

我唯一能想到的就是在服务器端和客户端都填充商店。

服务器端已经覆盖了nuxtServerInit。

客户端可以使用客户端插件来完成,如此处所述:https : //github.com/nuxt/nuxt.js/pull/4573#issuecomment-557857101

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android