如何通过单击页面上的按钮来触发服务器发送SSE?

时间:2016-09-30 17:58:05

标签: javascript html node.js server-sent-events

我正在学习服务器发送的事件,并想尝试我自己的例子。我发现的所有示例都设置了一个服务器,它只使用一个间隔将新事件发送到HTML页面上的EventSource。我想做的是在页面上有一个按钮,调用服务器,触发一个新的事件发送到EventSource对象。

的index.html

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Home</title>
</head>
<body>
    <h1>Home</h1>

    <div id="click-container">

    </div>

    <script type="text/javascript">
        var source = new EventSource('/clicks');
        var clickContainer = document.getElementById("click-container");
        source.addEventListener("message", function(e) {
            clickContainer.innerHTML = e.data + '<br>';
        });
    </script>

    <h1>Clicker</h1>

    <button type="button" id="clicker">Click Me</button>

    <script type="text/javascript">
        var btn = document.getElementById("clicker");

        btn.addEventListener("click", function(e) {
            var req = new XMLHttpRequest();
            req.onreadystatechange = function() {
                if (xhr.readyState == XMLHttpRequest.DONE) {
                    console.log(req.responseText);
                }
            };

            req.open('GET', '/click', true);
            req.send(null);
        });
    </script>
</body>

但对于我在Node中所做的服务器,我不知道该怎么做。我已经尝试将请求发送到EventSource正在侦听的相同URL,但这只会导致该请求陷入开放连接并且永远不会完成。我只是无法绕过我需要做的事情,我能解释一下这应该如何运作吗?感谢

2 个答案:

答案 0 :(得分:1)

您需要使用类似Redis的东西作为您的发布/订阅代理。我写了一篇关于如何使用Node进行此操作的两部分博客系列。

  1. Part 1
  2. Part 2

答案 1 :(得分:0)

为此,您可以使用fetch()

client.js:

document.getElementById("clicker").onclick = function() {
  data = { somenthing: "123"}
  fetch("/sendData", {
    method: "POST",
    body: data,
    headers: { "Content-Type": "application/json"
  }).then(res => res.json())
  .then(resp => {
    //do something with returned data
    alert(resp) // { message: "hello" }
  })
}

server.js:

const express = require("express")
const app = express()
const bodyParser = require("body-parser")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.post("/sendData", (req, res) => {
  console.log(req.body.something) // "123"

  //return a response to the client side
  res.send({ message: "hello" })
})