简体   繁体   English

如何从后端通知前端?

[英]How to notify front-end from backend?

I am using multer for file uploading.我正在使用 multer 进行文件上传。 On the server I have this:在服务器上我有这个:

stream.on('finish', () => {                                                                              
  console.log('finished')                                                                                
  next()
})

What would be the best way (with what command) to notify the frontend that 'finished' has happened?通知前端“完成”已经发生的最佳方式(使用什么命令)是什么? I want to know this in order to have a loading bar.我想知道这个以便有一个加载栏。

That's what websockets are for. 这就是websocket的用途。 The server can send data to the client, and vice-versa. 服务器可以将数据发送到客户端,反之亦然。 Check out socket.io . socket.io

Server : socket.emit("upload finished") 服务器: socket.emit("upload finished")

Client : socket.on("upload finished", function...) 客户端: socket.on("upload finished", function...)

While Jeremy Thille 's answer works well, beware of broadcasting event to all. 尽管杰里米·蒂尔Jeremy Thille )的答案很好用,但请注意向所有人广播事件。

Socket.emit() simply broadcasts message to all connected clients. Socket.emit()只是向所有连接的客户端广播消息。

So you need to store the client id of the uploader and notify the progress only to that client and not all. 因此,您需要存储上载器的客户端ID,并仅将进度通知给该客户端,而不是全部。 Refer this . 请参考

You can use sockets for this type of communication. 您可以将套接字用于这种类型的通信。 socket.io is a node package for web sockets. socket.io是Web套接字的节点程序包。 In the server you have 在服务器中

socket.emit('done')

whereas in the client side you can attach to the emit to receive new data 而在客户端,您可以附加到发射以接收新数据

socket.on('done', function (data) {
    // Do something with data
}); 

Well, I know I am 5 years 7 months late but still I want to share my opinion.好吧,我知道我晚了 5 年 7 个月,但我仍然想分享我的意见。 Socket is a really good approach but another way can also be SSE(Server Sent Events) to automatically notify the frontend via HTTP but you can notify the frontend using only text message.套接字是一种非常好的方法,但另一种方法也可以是 SSE(服务器发送事件)通过 HTTP 自动通知前端,但您可以仅使用文本消息通知前端。

For FrontEnd:对于前端:

  1. First you have to create eventsource object.首先你必须创建事件源 object。
let sse = new EventSource(
       "URL for backend",
        { withCredentials: true }
      )

here credential is for the cookie to pass.这里的 credential 是为了让 cookie 能够通过。

2.Now add eventListeners to get the result from backend. 2.现在添加事件监听器以从后端获取结果。

see.onmessage = (e)=>{
let data = JSON.parse(e.data)
//now do whatever you want with the data
}

For Backend:对于后端:

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}`);
});

So this is basically the whole thing.所以这基本上就是整个事情。 I am attaching a link which helped me to understand the SSE.我附上了一个帮助我了解 SSE 的链接。 https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app https://www.digitalocean.com/community/tutorials/nodejs-server-sent-events-build-realtime-app

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

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