javascript - 在 Next.js + Redux-saga 中刷新窗口时如何设置授权标头?
问题描述
我正在尝试使用 JWT Bearer 令牌设置授权标头。
刷新窗口时,标题被重置。我从 localstorage 设置了“componentDidMount”时的标题,但是重复了很多并且从预渲染中获得了未定义的 localstorage。
axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('accesstoken');
如何以及在哪里可以添加全局函数来设置标头与本地存储的值?或任何其他好的解决方案?
解决方案
我从您的问题中看到您正在使用,因此您可以实现负责在 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 的出色身份验证流程配方。
推荐阅读
- reactjs - 反应不加载背景图像
- ios - 连接 VPN IKEv2 它可以在 iOS 平台上工作,但 macOS 无法工作,面临同样的问题
- python-3.x - 同一画布上的多个图形
- mysql - 从条件相同的表中获取列名
- android - 为容器中的两个孩子绘制阴影,它们之间没有空间
- python - 在不调用 super() 的情况下执行父类方法
- azure - 使用类似于 zipkin 的 Azure 日志分析跟踪 REST 跟踪时间的可能性
- django - 如何将多个对象作为上下文传递给 django 中基于类的通用视图中的模板?
- reactjs - 如何使用 React Native 显示 ASP.NET Core 返回的非公共图像?
- javascript - 文本甚至没有使用 typed.js 输入