简体   繁体   English

nodejs在不刷新页面的情况下从api获取响应

[英]nodejs get response from api without refreshing page

EDIT: I started nodejs few days ago and i want to understand one thing.编辑:几天前我开始使用 nodejs,我想了解一件事。 Imagine that i have a nodejs web communicate with API, when i send request (offer for a specific user) i would like to know if user has accepted or declined the offer without refreshing the site.想象一下,我有一个 nodejs 网络与 API 通信,当我发送请求(针对特定用户的提议)时,我想知道用户是接受还是拒绝了提议,而无需刷新站点。 I know there is a way with AJAX, but is there any better solution how can i get state of the offer if it is accepted/declined (if something change)我知道有一种使用 AJAX 的方法,但是有没有更好的解决方案,如果它被接受/拒绝(如果有什么变化),我如何获得报价的状态

Every advice is appreciated!每一个建议都值得赞赏!

If you want to know in the client when the state of something on the server changes (at some indefinite future time), then here are three options:如果您想在客户端知道服务器上某物的状态何时发生变化(在某个不确定的未来时间),那么这里有三个选项:

  1. You can regularly "poll" the server every so often with an ajax call asking for any updates on the offer.您可以通过 ajax 调用定期“轮询”服务器,要求提供任何更新。 The server can then return the current state of the offer and the client can update the status in the current web page.然后服务器可以返回报价的当前状态,客户端可以更新当前网页中的状态。

  2. You can create a webSocket or socket.io (socket.io is an API on top of a webSocket) connection from the client to the server.您可以创建从客户端到服务器的 webSocket 或 socket.io(socket.io 是 webSocket 之上的 API)连接。 This is a long lasting connection which allows the server to send data to the client at any time.这是一个持久的连接,允许服务器随时向客户端发送数据。 So, anytime the server sees a change in the state of that offer, it can send an update to the client and the client can then modify the current page to show that change.因此,只要服务器看到该报价的状态发生变化,它就可以向客户端发送更新,然后客户端可以修改当前页面以显示该更改。

  3. You can use the newer server-sent events which is an extension to http which allows a server to send data to a client to accomplish something similar to the previous option.您可以使用较新的服务器发送事件,它是 http 的扩展,它允许服务器将数据发送到客户端以完成类似于前一个选项的操作。

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

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