Reactjs - 在 api 调用失败时注销/重定向用户 [英] Reactjs - logout/redirect user on failed api call

查看:16
本文介绍了Reactjs - 在 api 调用失败时注销/重定向用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Reactjs 构建了一个 Web 应用程序.我使用路由器和 redux 进行状态管理以进行身份​​验证.一切正常,但问题出在 api 调用上.在用户登录并调用 ... 服务后,我想检查服务的响应是否包含任何令牌问题(例如:令牌已过期).如果存在令牌问题,我想使令牌无效(将其删除)并将用户发送回带有错误消息的登录页面.现在,如果我在 redux action/reducer 中执行所有 api 调用,我就可以做到这一点.但是我不确定是否必须为每次调用都实现 redux,因为我不需要其他组件中的数据.而且在 redux 中实现所有服务也很耗时,需要大量代码.

I built a web app using Reactjs. I used router and redux for state management for authentication. Everything works fine BUT the problem is with api calls. After the user logged in and calls a ... service I want to check the response of the service wether it contains any token problem (example: token expired). If there is a token problem I want to invalidate the token (remove it) and sent the user back to the login page with an error message. Now, I can do this if I do all api calls inside my redux action/reducer. But I'm not sure if I have to implement redux for every call because I don't need the data in other components. And also implementing all services in redux is time consuming and needs a lot of code.

我将项目复制到 stackblitz.

I replicated the project to stackblitz.

https://stackblitz.com/edit/react-auth?file=index.js

场景很简单.单击登录,您就在应用程序中.该应用程序会自动调用服务并获得响应.如果您在 api.js 中将 URL 更改为错误的 URL,则此服务将提供40x"响应.当我收到此回复时,我想将用户重定向到登录页面.

Scenario is simple. Click on login and your are in the app. The app automatically calls a service and gets a response. If you change the URL to a faulty one inside api.js then this service will give a '40x' response. When I receive this response I want to redirect the user to the Login page.

有任何帮助/建议吗?

谢谢.

推荐答案

这是一个使用 axios 和你的 api.js 的例子:

Here is an example using axios and your api.js :

import axios from 'axios';

const apiKey = 'API_KEY';

export async function getWeather() {
  const url = `https://reqres.in/api/users?page=2`;
  axios.interceptors.response.use(handleSuccess, handleError)
  return await axios.post(url);
 }

function handleSuccess(response) {
  console.log('success');
  return ({data: response.data});
}

function handleError(error) {
  if (error.message === 'Network Error') {
     // The user doesn't have internet
      return Promise.reject(error);
   }
   switch (error.response.status) {
      case 400:
        break;
      case 401:
        // Go to login
        break;
      case 404:
        // Show 404 page
        break;
      case 500:
        // Serveur Error redirect to 500
        break;
      default:
        // Unknow Error
       break;
    }
    return Promise.reject(error);
}

因此,根据代码状态和​​您想要的代码答案行为,您应该重定向用户或仅向他显示一个模式.

So depending on the code status and the behavior you want for the code answer you should redirect the user or just show a modal to him.

查看 axios 拦截器

这篇关于Reactjs - 在 api 调用失败时注销/重定向用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆