javascript - 如何使用fetch客户端进行数据查询时401登出?

标签 javascript security xmlhttprequest fetch

在 Web 应用程序中,我正在重用 react-admin 网站上指定的 dataProvider:https://marmelab.com/react-admin/DataProviders.html#data-providers在另一个 react 应用程序中。

如果任何请求返回 401 响应,他们就能够断开连接并重定向到登录。

在我的其他非 react 管理应用程序中,当我的请求失败( session 超时)时,我没有此重定向。

这就是我的dataProvider的样子:

const dataProvider = {
    getList:    (resource, params) => Promise,
    getOne:     (resource, params) => Promise,
    getMany:    (resource, params) => Promise,
    getManyReference: (resource, params) => Promise,
    create:     (resource, params) => Promise,
    update:     (resource, params) => Promise,
    updateMany: (resource, params) => Promise,
    delete:     (resource, params) => Promise,
    deleteMany: (resource, params) => Promise,
}

我已经 checkin 了代码,我希望看到每个方法的包装器,它将添加 catch 并在必要时触发重定向以登录。

相反,我没有看到这一点,我想知道为什么以及如何在我的应用程序中正确解决这个问题。

最佳答案

如果没有任何其他代码,就不能说很多。需要更多的东西以便我们可以重现。 Promise 是否直接引用您正在使用的 Promise 库?具体答案完全取决于您拥有的架构和其他支持库。

这些是我们使用 reduxreact-router-dom 的步骤

  1. 身份验证/数据请求失败
  2. 销毁本地存储凭据。
  3. 通过 LogoutAction 触发副作用/应用状态更改
  4. 使用应用状态更新 redux 存储。
  5. 高阶组件PrivateRoute包装了所有需要私有(private)的路由。它检查 isLoggedIn 状态并返回页面组件或将用户重定向到 /login

例如

// handle promise error
    private handleError = (errorMessage: Error) => {
        const message = JSON.parse(errorMessage.message);
        if (message.status === 401) {

            this.authentication.logout(); // triggers logout actions and destroy credentials
        }
        throw errorMessage;
    }

    private destroyUserCredentials() {
        this.tokenResponse = null;
        this.tokenClaims = null;
        this.tokenHasExpired = true;
        this.accessToken = null;
        this.localStorage.removeItem(this.storageKey);
    }

 // dispatch action to change redux store state
 appStore.dispatch(LogOutAction());
// Private route HOC
export const PrivateRouteComponent = ({ component: Component, state: state, ...rest }) => {
    const renderComponent = (props) => {
        if (state.login.isLoggedIn) {
            return <Component {...props} />;
        } else {
            return <Redirect to='/login' />;
        }
    };

    return (
      <Route
        {...rest}
        render={renderComponent}
      />
    );
  };

// REF: pluralsight connect container
function mapStateToProps(state, ownProps) {
    return {
        state: {
            login: state.authenticate
        }
    };
}

export const PrivateRoute = connect(mapStateToProps)(PrivateRouteComponent);

// Route setup
 <Provider store={appStore}>
            <BrowserRouter>
                <Switch>
                    <Route path='/login' component={LoginPage} />
                    <PrivateRoute path='/analytics' component={HomePage} />
                    <PrivateRoute path='/account' component={AccountPage} />
                </Switch>
            </BrowserRouter>
        </Provider>

关于javascript - 如何使用fetch客户端进行数据查询时401登出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61467790/

相关文章:

javascript - 热衷于使用 jQuery 将 html 输入属性映射到对象?

PHP:$_FILES 中 'type' 索引的来源是什么?

java - 在 Sax 解析器 (XML) 中处理外部实体和样式表

javascript - 从jsp加载servlet并尝试传递多个参数

javascript - 自定义标题 Angular js

javascript - 尝试附加到文档时,responseXML 中缺少 head 子项

javascript - Wistia Javascript API - 重定向到确认页面的转换事件

javascript - 将英语数字转换为波斯语

javascript - windows live 登录 获取电子邮件地址

security - 如果服务器上启用了内容安全策略,如何使用小书签将脚本注入(inject)页面?