reactjs - 如何防止 axios.interceptors.response.use 崩溃错误处理?

标签 reactjs axios

我有几种形式“登录、注册、创建产品...”对于这些形式,我在前端使用 useState 处理错误,在后端使用 express-validator 处理错误。

一切正常,我收到了预期的错误消息。

但是现在,我意识到这些表单都不再管理错误了。由于我设置了我的 axios.interceptors.response.use 以在用户处于 403 状态时将用户发送回登录页面(这是我处理过期 token 的方式)。

这是我的代码,通常会向我显示错误: (例如,这是我的登录页面,我只收到一条错误消息)

axios.interceptors.request.use(
  (config) => {
    config.headers.authorization = `Bearer ${localStorage.getItem('UserToken')}`;
    return config;
  },
  (error) => {
    return Promise.reject(error);
  },
);

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 403) {
      localStorage.clear();
      window.location.href = '/connexion';
    }
  },
);

export default function ConnexionPage() {
  // Redirection Connexion réussite vers Accueil
  const history = useHistory();

  const [errorForm, setErrorForm] = useState();

  // Connexion
  const handleSubmit = (event) => {
    event.preventDefault();
    login(event.target.email.value, event.target.password.value)
      .then((response) => {
        const Token = response.data.accessToken;
        localStorage.setItem('UserToken', Token);
        User = jwt_decode(Token);
        localStorage.setItem('User', JSON.stringify(User));
        history.push({
          pathname: '/',
        });
        window.location.reload(false);
      })
      .catch((err) => {
        setErrorForm(err.response.data);
      });
  };

  // Classe de style
  const classeConnexion = ConnexionStyle();

  return (
    <Grid>
      <Card style={{ height: 500, marginTop: '5%', marginRight: '10%', marginLeft: '10%' }} variant="outlined">
        <Grid align="center">
          <Avatar className={classeConnexion.avatar}>
            <LockOutlinedIcon></LockOutlinedIcon>
          </Avatar>
          <h2>Connexion :</h2>
          {errorForm && <p style={{ color: 'red' }}>{errorForm}</p>}
        </Grid>

        <form onSubmit={handleSubmit}>
          <TextField
            id="email"
            name="email"
            label="Email :"
            placeholder="Entrez votre mail."
            fullWidth
            variant="outlined"
            style={TextFieldStyle}
            required
          />

          <TextField
            style={TextFieldStyle}
            id="password"
            name="password"
            label="Mot de passe :"
            placeholder="Entrez votre mot de passe."
            type="password"
            fullWidth
            variant="outlined"
            required
            autoComplete="on"
          />

          <Button endIcon={<CheckIcon />} className={classeConnexion.root} type="submit" variant="contained" fullWidth>
            Connexion
          </Button>
        </form>

        <Typography>
          <Link href="/inscription">Pas de compte ? Créez-en un.</Link>
        </Typography>
      </Card>
    </Grid>
  );
}

PS:我还是一个单纯的学生,要做一个电商网站作为练习。

编辑: 是的,是我的 axios.interceptors.response.use 导致我的错误处理被忽略或导致应用程序崩溃

最佳答案

你错过了一件事,当 error.response.status 不是 403 时从 axios 响应拦截器返回错误

axios.interceptors.response.use(
  (response) => response,
  (error) => {
    if (error.response.status === 403) {
      localStorage.clear();
      window.location.href = "/connexion";
    }

    // reject with error if response status is not 403
    return Promise.reject(error);
  }
);

);

关于reactjs - 如何防止 axios.interceptors.response.use 崩溃错误处理?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67755260/

相关文章:

javascript - 禁用 create-react-app 的 SKIP_PREFLIGHT_CHECK 有缺点吗?

javascript - Gatsby 在单击按钮时打开模态窗口

javascript - axios Get 请求问题

reactjs - React useEffect使用axios获取数据后返回空数组

javascript - axios 在状态 200 上返回错误

javascript - 如何使状态可迭代并解析 "Unhandled Rejection (TypeError): state.story is not iterable"?

javascript - Flux 和 React JS 中的依赖操作

javascript - Laravel Vue Axios 未定义

javascript - 尝试刷新 token 时 Axios 拦截器无限循环

javascript - 如何存储获取的数据