在Next.js + Redux-saga中刷新窗口时如何设置授权标头?

问题描述 投票:0回答:1

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

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

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

如何以及在何处可以添加将标头设置为localstorage值的全局函数?或任何其他好的解决方案?

javascript react-redux next.js redux-saga prerender
1个回答
0
投票

[我从您的问题中看到您正在使用redux-saga,因此您可以实现auth flow saga,它负责在api客户端中设置JWT令牌,并且将在应用程序引导期间被调用,而不是在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(authSaga),
  ]);
}

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

© www.soinside.com 2019 - 2024. All rights reserved.