[英]How to notify front-end from backend?
我正在使用 multer 进行文件上传。 在服务器上我有这个:
stream.on('finish', () => {
console.log('finished')
next()
})
通知前端“完成”已经发生的最佳方式(使用什么命令)是什么? 我想知道这个以便有一个加载栏。
尽管杰里米·蒂尔 ( Jeremy Thille )的答案很好用,但请注意向所有人广播事件。
Socket.emit()
只是向所有连接的客户端广播消息。
因此,您需要存储上载器的客户端ID,并仅将进度通知给该客户端,而不是全部。 请参考此 。
您可以将套接字用于这种类型的通信。 socket.io是Web套接字的节点程序包。 在服务器中
socket.emit('done')
而在客户端,您可以附加到发射以接收新数据
socket.on('done', function (data) {
// Do something with data
});
好吧,我知道我晚了 5 年 7 个月,但我仍然想分享我的意见。 套接字是一种非常好的方法,但另一种方法也可以是 SSE(服务器发送事件)通过 HTTP 自动通知前端,但您可以仅使用文本消息通知前端。
对于前端:
let sse = new EventSource(
"URL for backend",
{ withCredentials: true }
)
这里的 credential 是为了让 cookie 能够通过。
2.现在添加事件监听器以从后端获取结果。
see.onmessage = (e)=>{
let data = JSON.parse(e.data)
//now do whatever you want with the data
}
对于后端:
const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const PORT = 5000;
let clients = [];
const event = (req, res) => {
const headers = {
'Content-Type': 'text/event-stream',
'Connection': 'keep-alive',
'Cache-Control': 'no-cache',
}
res.writeHead(200, headers)
let message = { event_name: 'ONGOING' }
const data = `data: ${JSON.stringify(facts)}\n\n`
res.write(data)
const clientId = Date.now()
const newClient: Client = {
id: clientId,
response: res,
}
clients.push(newClient)
req.on('close', () => {
console.log(`${clientId} Connection closed`)
clients = clients.filter((clients: Client) => clients.id !== clientId)
})
};
const notifyEvent = ()=>{
let newMessage = { event_name: 'FINISHED' }
const data = `data: ${JSON.stringify(newMessage)}\n\n`
// Send a message to each client
clients.forEach((client) => client.response.write(data))
}
//Here goes your part
stream.on('finish', () => {
console.log('finished')
return notifyEvent()
next()
})
app.get("/event", event);
app.listen(PORT, () => {
console.log(`App listening on port ${PORT}`);
});
所以这基本上就是整个事情。 我附上了一个帮助我了解 SSE 的链接。 https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.