简体   繁体   English

如何在 Express 中发送响应

[英]How to send a response in Express

I am using express and MongoDB and want some real-time updates whenever any change happens in my DB.我正在使用 express 和 MongoDB 并希望在我的数据库中发生任何更改时进行一些实时更新。 I use MongoDB change stream.我使用 MongoDB 更改 stream。 But when I put my change function inside the route it only sends a response when I hit my route, and when I put the change function outside of the route I am unable to send a response.但是,当我将更改 function 放在路线内时,它只会在我到达路线时发送响应,而当我将更改 function 放在路线之外时,我无法发送响应。

So my problem how to send a response when any change happens in my collection.所以我的问题是当我的收藏发生任何变化时如何发送响应。

const testSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
});

const model = mongoose.model('test', testSchema);

//change 
model.watch().on('change', (data) => {
  console.log(data);
});

router.put('/update', async (req, res) => {
  const data = req.body;
  const info = await model.updateOne(data);
  res.send(info);
});

Whats you're trying to achieve relies on Web socket .您要实现的目标依赖于Web socket
Sockets are the way in which you can make applications communicate across network. Sockets是您可以使应用程序跨网络通信的方式。

Your browser uses socket programming.您的浏览器使用套接字编程。 It establishes a connection with the server on port 80(only for HTTP requests) and gets data from the server and displays it according to the markup.它在 80 端口与服务器建立连接(仅适用于 HTTP 请求)并从服务器获取数据并根据标记显示。

If you had played any online games like, Counter-Strike for example, where you had been a host then you would have understood its usage.如果您曾经玩过任何在线游戏,例如反恐精英,您曾经是其中的主持人,那么您就会了解它的用法。 You establish yourself as a host with certain port allocated to communicate.您将自己建立为分配了特定端口以进行通信的主机。 The game then passes data using that socket to other computers.然后游戏使用该套接字将数据传递给其他计算机。

You'll have to learn and understand SocketIO to achieve this.您必须学习和理解SocketIO才能实现这一目标。

Most of the lessons out there are being explained how it can be used for chat applications.大多数课程都在解释如何将其用于聊天应用程序。 But if you understand it better, you'll be able to build anything upon socket.但是,如果您更好地理解它,您将能够在套接字上构建任何东西。

Solution: server-sent events解决方案:服务器发送的事件

While you can also solve your issue using websockets, server-sent events are simpler to implement.虽然您也可以使用 websockets 解决您的问题,但服务器发送的事件更易于实现。 See this answer看到这个答案

const mongoose = require("mongoose");
const express = require("express");
const app = express();
const testSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true },
});

const model = mongoose.model("test", testSchema);

model.watch().on("change", (data) => {
  console.log(data);
});

app.put("/update", async (req, res) => {
  const data = req.body;
  const info = await model.updateOne(data);
  res.send(info);
});

app.get("/changes", async (req, res) => {
  res.writeHead(200, {
    "Content-Type": "text/event-stream",
    "Cache-control": "no-cache",
    "Access-Control-Allow-Origin": "*",
  });
  const changeHandler = (data) => {
    res.write(`data: ${JSON.stringify(data)}\n\n`);
  };
  model.watch().on("change", changeHandler);
  res.on("close", () => {
    model.watch().removeListener("change", changeHandler);
    res.end();
  });
});
app.listen(4000);

And the html: html:

<!DOCTYPE html>
<html>
  <body>
    <script>
      const eventSource = new EventSource("http://localhost:4000/changes");
      eventSource.onmessage = (e) => {
        console.log(e);
      };

      eventSource.onerror = (e) => {
        console.log("EventSource failed.");
      };
    </script>
  </body>
</html>

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

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