【问题标题】:How to have a custom 401 page in React .net core API如何在 React .net 核心 API 中自定义 401 页面
【发布时间】:2021-06-11 18:36:27
【问题描述】:

当我获得 401 状态时,如何显示自定义 React 组件? 这是路线

        <Route path='/customErrorPage' component={ErrorPage} />

401 发生时如何触发该路由? (或其价值的任何特定错误代码) 这是我如何调用 api 并获得未经授权的 401。假设以下将发回 401 错误。在 JS 中:

        var res = await axios.get("api/access/validateme");

【问题讨论】:

    标签: asp.net-core asp.net-core-webapi


    【解决方案1】:

    最常见的方法是编写一个拦截器。

    拦截器是一种让每个 Axios 调用都运行的方法。你可以在这里阅读它们:https://github.com/axios/axios#interceptors

    你想要这样的东西:

    // Add a response interceptor
    axios.interceptors.response.use(function (response) {
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response;
      }, function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        if (401 === error.response.status) {
            route('/customErrorpage');
        } else {
            return Promise.reject(error);
        }
      });
    

    这是一个拦截器,可以捕获所有错误,特别是在 401 上,它会路由到您的页面。现在你还没有说你正在使用什么路由库,但我几乎保证它会有类似route() 的东西,只是一个以编程方式路由用户的函数。

    【讨论】:

      猜你喜欢
      • 2020-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-16
      • 1970-01-01
      相关资源
      最近更新 更多