node.js - 如何使用 NodeJs 监听和订阅 HTTP 事件?
问题描述
我正在尝试创建发票,然后通过订阅事件来跟踪其状态。我为此使用了 bitpay REST API,并且我已经成功创建了发票并成功检索了总线令牌。
这就是bitpay 文档所说的:
Once you have retrieved the bus pass, It's pretty simple. Send a GET request to the path configured for the bus - let's say it's bitpay.com/events including the appropriate parameters:
?token= - your "bus pass" retrieved from the API
&action= - usually "subscribe", but options are provided in your bus pass
&events[]= - an array of events to listen for (also provided in the bus pass)
Once you've opened the connection, you'll want to listen for chunks of data to be passed to you. Each chunk represents an event. Since the bus adheres to the SSE/EventSource specification, chunks are passed back in the format:
event: <event_type>
data: {"some":"json"}
如何收听这些事件?当我点击我要收听的链接时,我看到的是:
:
retry: 2000
event: connect
data: {"status":"subscribed","resource":"Sg9hggVxgC1VTKsGYqNyVT","facade":"public/invoice","events":["payment","confirmation","paymentRejected","scanned","paymentPosted"]}
event: state
data: {"url":"https://test.bitpay.com/invoice?
...
这是我尝试过的:
const evtSource = new EventSource('<path>');
evtSource.onmessage = (e) => {
console.log(e);
}
和
axios({
url : '<path>',
method: 'get',
connect: function(event){
console.log(event);
}
})
谢谢!
编辑:这是我想听的示例链接。
解决方案
这是一个工作示例 Codesandbox 演示https://codesandbox.io/s/gifted-borg-365z2?file=/app.js:0-496
const EventSource = require("eventsource");
const eventSourceInitDict = { https: { rejectUnauthorized: false } };
const evtSource = new EventSource(
"https://test.bitpay.com/events?token=767cdhmwtn7XgW1QrSkuEweXC3dUyCRcZqwvcGRvSeaDZh8UXj9aCcS1xPPppjaFYH&action=subscribe&events[]=payment&events[]=confirmation&events[]=paymentRejected&events[]=scanned&events[]=paymentPosted",
eventSourceInitDict
);
evtSource.addEventListener("connect", function (e) {
console.log("connect", e.data);
});
LOGS: connect {"status":"subscribed","resource":"HZxbCd5YRWnWJ4kK72DBai","facade":"public/invoice","events":["payment","confirmation","paymentRejected","scanned","paymentPosted"]
所以我猜在连接事件之后你可以订阅其他事件,如下所示:
evtSource.addEventListener("payment", function (e) {
console.log("payment", e.data);
});
尝试代替:
const evtSource = new EventSource('<path>');
evtSource.onmessage = (e) => {
console.log(e);
}
更新:https ://developer.mozilla.org/en-US/docs/Web/API/EventSource
const sse = new EventSource('<path>');
sse.addEventListener('<event>', function(e) {
console.log(e.data)
});
推荐阅读
- javascript - 使用 set-Attribute 设置 ng-pattern 不起作用
- html - 如何将html表单数据解析成文档
- angularjs - 如何解决 angularJs 可访问性中的断开链接?
- android - 可能未处理的 Promise Rejection (id:0) 错误:本机反应中的网络错误
- rest - RESTFul API 设计建议
- node.js - 将大文件上传到 Amazon S3 会在两分钟后创建两个副本
- c# - 无法将动态 DataTable 绑定到 Grid.MVC
- c# - 正规化瑞典货币的正则表达式
- c++ - std::cin 作为 while 循环条件的奇怪行为
- eclipse - 将 window tester 与 eclipse 集成以测试 UI