简体   繁体   English

如果 error.status == 401,如何重定向用户?

[英]How redirect user if error.status == 401?

My goal is to redirect users if the code of request is equal to 401. I wrote follow code but it display me error 401. It displays me 401 (from console.log but below error).我的目标是在请求代码等于 401 时重定向用户。我编写了以下代码,但它显示错误 401。它显示 401(来自 console.log 但低于错误)。 How can I implement redirection, if the error is equal to 401?如果错误等于 401,我如何实现重定向?

import axiosConfig from "../../config/axios";
import actions from "./actions";
import { Redirect } from "react-router";
const fetchUser = async () => {
    const response = await axiosConfig.get('api/get-user')
        .catch(function (error) {
            console.log(error.response.status) // 401
            console.log(error.response.data.error) //Please Authenticate or whatever returned from server
            if (error.response.status == 401) {
                return(
                    <Redirect
                        to={{
                            pathname: '/login',
                            state: { from: location },
                        }}
                    />
                );
            }
        });
    return response.data
}
export const getUser = () =>
    async (dispatch) => {
        const user = await fetchUser()
       dispatch(actions.setUser(user));
    }

@Update Routing setup @Update 路由设置

const Container = () => {
    return (
        <div className="container">
                            <Router>
                                <Switch>
                                    <Route path="/login">
                                        <Login />
                                    </Route>
                                    <Route path="/register">
                                        <Login />
                                    </Route>
                                        <Route path="/all-users">
                                            <Alltasks />
                                        </Route>
                                        <Route path="/all-articles">
                                            <AllUsers />
                                        </Route>
                                </Switch>
                            </Router>
                            <ToastContainer />
        </div>
    );
}

You can't return a Redirect component from an action, utility, or callback like this and expect it to be rendered and effect a redirect to a new route.您不能像这样从操作、实用程序或回调返回Redirect组件,并期望它被渲染并实现到新路由的重定向。 Your option is to access the history object and invoke an imperative redirect.您的选择是访问history object 并调用命令式重定向。

Option 1选项1

Connect your router to redux with connected-react-router .使用connected-react-router将您的路由器连接到 redux。 The basic gist is to create a custom "createRootReducer" function, create a history object, use the "ConnectedRouter" component.基本要点是创建自定义“createRootReducer”function,创建history object,使用“ConnectedRouter”组件。 This allows you to dispatch redux actions to effect navigation actions in your app.这允许您分派 redux 操作来影响应用程序中的导航操作。

Follow the steps to setup and connect routing to your redux store.按照步骤设置路由并将其连接到您的 redux 商店。

To use in your asynchronous action:在您的异步操作中使用:

import { replace } from 'connected-react-router';

...

const fetchUser = async () => {
  try {
    const response = await axiosConfig.get('api/get-user');
    return response.data;
  } catch (error) {
    if (error.response.status == 401) {
      throw new Error(error);
    }
  }
}

export const getUser = () => async (dispatch) => {
  try {
    const user = await fetchUser();
    dispatch(actions.setUser(user));
  } catch {
    dispatch(replace('/login'));
  }
}

Option 2选项 2

Create a history object and import and use in getUser action.创建历史记录 object 并在getUser操作中导入和使用。

Create a memory, hash, or browser history object:创建memory、hash,或者浏览器历史记录object:

import { createBrowserHistory } from 'history';

export const history = new createBrowserHistory();

Import the plain Router from react-router and pass the history object as prop:react-router导入普通Router并将历史记录 object 作为 prop 传递:

import { Router } from 'react-router';
import { history } from '../path/to/custom/history';

...

<Router history={history}>
  ...
</Router>

Import and use history in the getUser action:getUser操作中导入和使用history

import { history } from '../path/to/custom/history';

...

const fetchUser = async () => {
  try {
    const response = await axiosConfig.get('api/get-user');
    return response.data;
  } catch (error) {
    if (error.response.status == 401) {
      throw new Error(error);
    }
  }
}

export const getUser = () => async (dispatch) => {
  try {
    const user = await fetchUser();
    dispatch(actions.setUser(user));
  } catch {
    history.replace('/login');
  }
}

Option 3选项 3

Pass the history object to the getUser action.history object 传递给getUser操作。

const fetchUser = async () => {
  try {
    const response = await axiosConfig.get('api/get-user');
    return response.data;
  } catch (error) {
    if (error.response.status == 401) {
      throw new Error(error);
    }
  }
}

export const getUser = (history) => async (dispatch) => {
  try {
    const user = await fetchUser();
    dispatch(actions.setUser(user));
  } catch {
    history.replace('/login');
  }
}

Usage:用法:

import { useHistory } from 'react-router-dom';

...

const history = useHistory();

...

getUser(history);

...

const mapDispatchToProps = {
  getUser,
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 为什么 axios.interceptors.response.use 不包含 error.status - Why axios.interceptors.response.use was not contain a error.status 当用户想要登录时:AXIOS 错误:[错误:请求失败,状态码 401] BAD_REQUEST - when user want to login : AXIOS ERROR: [Error: Request failed with status code 401] BAD_REQUEST 如何根据 Firebase 身份验证状态重定向用户? - How to redirect a user based on Firebase Authentication status? 如何在axios模拟适配器中返回自定义401错误状态 - How to return custom 401 error status in axios mock adapter React Redux操作文件中的重定向401错误 - Redirect 401 Error in React Redux Actions File 如何使用 axios 在反应中处理状态 401? - how to handle status 401 with axios in react? 如何在React-Router中从ajax调用中获取401错误时重定向到登录页面? - How redirect to login page when got 401 error from ajax call in React-Router? 如何使用expressjs重定向以获取特定状态? - How to redirect with expressjs for a specific status? Reactjs 错误:未捕获(承诺中)错误:请求失败,状态码为 401 - Reactjs error: Uncaught (in promise) Error: Request failed with status code 401 使用邮递员登录时如何解决401未经授权的状态 - How to fix 401 unauthorized status when logged in using the postman
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM