如何解决如何将数据从控制器功能推送到我的前端? (Nodejs + 反应)
我已经实现了一个 Nodejs 服务器和一个 React 前端。同时,我的服务器正在侦听从其他设备发送的 webhooks 数据。问题是,我需要获取这些数据并将其(实时)推送到前端。
我已经尝试过 socket.io 和 Server-Sent Events(我遵循了本教程:https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app),但我无法让它工作。
我启用了一个路由(例如:router.post('/webhooks/radio-events',webhooks.consultarRadioEvents)
)来发送数据,以及一个关联的控制器。控制器代码为:
const webhookCtrl= {};
webhookCtrl.consultarRadioEvents = (req,res) => {
var webhooksData = req.body.data; // This is the data I receive from the other device
// Now I should send the data to my frontend
};
我尝试的是以下内容:(服务器发送事件)
服务器端:
function eventsHandler(req,res,next) {
// Mandatory headers and http status to keep connection open
const headers = {
'Content-Type': 'text/event-stream','Connection': 'keep-alive','Cache-Control': 'no-cache'
};
res.writeHead(200,headers);
const data = `data: DATA TO SEND\n\n`; //Here I have to put the real data from webhooks
res.write(data);
}
// Define endpoints
app.get('/events',eventsHandler)
前端:
import React from 'react'; import{Fragment,useEffect} from 'react'
const WebhooksDataTable =()=>{
const eventSource = new EventSource('http://localhost:4000/api/events')
useEffect(()=>{
eventSource.onmessage = (event) => {
console.log(event.data) //Here I print the data pushed from the server
};
},[eventSource]) // eslint-disable-line react-hooks/exhaustive-deps
return(
//Here I make the table with the data sent from the server
) }
使用此解决方案,我可以将数据发送到前端,但我不知道如何在每次 webhookCtrl.consultarRadioEvents
执行时发送/推送数据。
如果您需要更多详细信息,请询问我。 提前致谢
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。