使用 nuxtServerInit 时缓存的访问令牌

jdl*_*dlm 5 akamai nuxt.js

使用 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);
    }
  },
};
Run Code Online (Sandbox Code Playgroud)

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}`;
    }
  });
};
Run Code Online (Sandbox Code Playgroud)

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

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

Har*_*hah 2

尝试在每个请求的标头下方添加,这样它就不会缓存标头

config.headers['Cache-Control'] = 'private, no-cache, no-store, must-revalidate';
Run Code Online (Sandbox Code Playgroud)