首页 > 解决方案 > 在 Next.js + Redux-saga 中刷新窗口时如何设置授权标头?

问题描述

我正在尝试使用 JWT Bearer 令牌设置授权标头。

刷新窗口时,标题被重置。我从 localstorage 设置了“componentDidMount”时的标题,但是重复了很多并且从预渲染中获得了未定义的 localstorage。

axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('accesstoken');

如何以及在哪里可以添加全局函数来设置标头与本地存储的值?或任何其他好的解决方案?

标签: javascriptreact-reduxnext.jsredux-sagaprerender

解决方案


我从您的问题中看到您正在使用,因此您可以实现负责在 api 客户端中设置 JWT 令牌并将在应用程序引导期间调用的身份验证流传奇,redux-saga而不是在其中包含此逻辑:componentDidMount

function* authSaga() {
  // This part will be invoked only once during the app startup
  const token = JSON.parse(localStorage.getItem('accessToken'));
  if (token) {
    axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
  }

  // Further auth flow logic goes here
  while(true) {
    if (!token) {
      const { payload } = yield take(SIGN_IN_ACTION);
      yield call(axios.post, '/your-sign-in-endpoint', payload);
    }

    yield take(SIGN_OUT_ACTION);
     // etc
  }
}

function* rootSaga() {
  yield all([
    fork(saga1),
    fork(saga2),
    ...
    fork(authSaga),
  ]);
}

此外,我强烈建议您参考这个线程,其中包含使用 redux-saga 的出色身份验证流程配方。


推荐阅读