使用 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__变量?
尝试在每个请求的标头下方添加,这样它就不会缓存标头
config.headers['Cache-Control'] = 'private, no-cache, no-store, must-revalidate';
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
597 次 |
| 最近记录: |