简体   繁体   English

使用 Nodejs 向客户端发送消息

[英]Send messages to client with Nodejs

I have a server side application, which implements Rest API for client Http requests.我有一个服务器端应用程序,它为客户端 Http 请求实现 Rest API。

I have a request for deleting MongoDB docs for many schemas.我请求删除许多模式的 MongoDB 文档。

I want to send to the client realtime object status about the delete proccessing like: Status: { xSchema: "DONE" } And then Status: { xSchame: "DONE", ySchame: "DONE" }我想向客户端发送有关删除处理的实时 object 状态,例如: Status: { xSchema: "DONE" } 然后 Status: { xSchame: "DONE", ySchame: "DONE" }

This object will send to the client When each step of the delete proccessing is done.当删除处理的每个步骤完成时,这个 object 将发送给客户端。

I thought about using socket.io for this operation, do you guys have any other ideas or example how to do it?我考虑过使用 socket.io 进行此操作,你们还有其他想法或示例吗? What's the best practices for this?这方面的最佳做法是什么?

I want to send these status without client requests.我想在没有客户请求的情况下发送这些状态。

Thanks for your help.谢谢你的帮助。

You can try to something like this, where you will be sending a result object with success status and status message in a json format to the client side.您可以尝试这样的操作,您将以 json 格式向客户端发送结果 object 以及成功状态和状态消息。

router.get('/profile/:username', (req, res, next) => {
  User.findOne({ username: req.params.username }, (err, user) => {
    if (err) {
      next(err);
    }
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.json({ success: true, status: 'User Retrieved Successfully!', user: user });
  })
});

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

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