简体   繁体   English

如何在 React 前端实现保活轮询?

[英]How to implement keep-alive polling in React frontend?

In my situation, we have Shibboleth authentication proxy that sits between the client and the server.在我的情况下,我们有位于客户端和服务器之间的 Shibboleth 身份验证代理。 Since there may be cases when a user takes a lot of time to fill out a page without causing any HTTP requests to be made, the Shibboleth may end their session possibly causing the user to lose their work.由于可能存在用户花费大量时间填写页面而没有发出任何 HTTP 请求的情况,Shibboleth 可能会结束他们的会话,从而可能导致用户丢失他们的工作。

To implement keep-alive polling I've made a route for that in our backend.为了实现保活轮询,我在后端为此制定了一条路线。 However, I have been unable to implement the actual polling in our React frontend.但是,我一直无法在我们的 React 前端实现实际的轮询。 How do I implement making repeated HTTP requests for as long as the app is open in a client browser?只要应用程序在客户端浏览器中打开,如何实现重复发出 HTTP 请求? The data returned from a keep-alive request is arbitrary and has no use in the frontend, thus this could possibly be done completely outside React. keep-alive 请求返回的数据是任意的,在前端没有用处,因此这可能完全在 React 之外完成。

Here is my implementation in case it is of any use to someone.这是我的实现,以防它对某人有用。 You want to refactor it a bit but the functionality is there.您想稍微重构它,但功能就在那里。 It uses React's useEffect hook to set/clear an interval timer that makes the keep-alive request to backend with axios .它使用 React 的useEffect钩子来设置/清除一个间隔计时器,该计时器使用axios向后端发出保持活动请求。 All encapsulated in a React component.全部封装在一个 React 组件中。

import React, { useEffect } from 'react';
import axios from 'axios';

/** Poll backend's keep-alive route every 5 minutes to maintain Shibboleth session. */
export default () => {
  const url = process.env.NODE_ENV === 'development' ? 'http://localhost:3001/keepalive' : '/keepalive';

  useEffect(() => {
    const interval = setInterval(() => axios.get(url), 5 * 60 * 1000);
    return () => clearInterval(interval);
  });

  return <div />;
};

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM