【问题标题】:"close" event did not fire in server sent events(sse) if i serve the index.html in the same origin如果我在同一来源提供 index.html,则服务器发送的事件(sse)中不会触发“关闭”事件
【发布时间】:2022-01-24 06:10:46
【问题描述】:

我正在尝试用server-sent-event 做一些演示,这是我的代码:
index.js

import http from "http";
import fs from "fs";
import path from "path";

http.createServer((req, res) => {
  const { url, method } = req;
  if (url === "/" && method === "GET") {
    res.writeHead(200, "ok", {
      "content-type": "text/html",
    });
    fs.createReadStream("./index.html")
      .pipe(res);
    return;
  } else if (url === "/favicon.ico" && method === "GET") {
    res.writeHead(404);
    res.end();
    return;
  } else if (url === "/sse") {
    if (method !== "GET") {
      res.writeHead(405);
      res.end("method not allowed");
      return;
    }
    res.writeHead(200, {
      "content-type": "text/event-stream",
      "cache-control": "no-cache",
      "connection": "keep-alive",
    });
    
    req.addListener("close", () => {
      console.log("close");
    });
    res.write("event: ping\n");
    res.write("data: hello world!\n\n");
    return;
  }

  // other url will be redirect to /
  res.writeHead(301, {
    location: "/"
  });
  res.end();
}).listen(8888, () => {
  console.log("\n\thttp://0.0.0.0:8888\n");
});

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <div>
    <h2>NodeJs HTTP</h2>
  </div>
  <script>
    const url = "/sse"; // if I use this relative url, then the listener in index.js will not fire. Why?
    // const url = "http://127.0.0.1:8888/sse"; // if I use absolute url, everything works fine.
    const sse = new EventSource(url);
    sse.addEventListener("open", function(e) {
      console.log(e)
    });
    sse.addEventListener("ping", function(e) {
      console.log(e);
    });
    sse.addEventListener("message", function(e) {
      console.log(e);
    });
    sse.addEventListener("error", function(e) {
      console.log(e);
    });
  </script>
</body>
</html>

如果我在 index.html 中使用绝对 url,一切都会按预期工作:

  1. 当我在浏览器中刷新/关闭当前选项卡时,控制台应该记录一个字符串 close。

但如果我使用相对 url,这些不会在控制台中输出。我想知道为什么会这样?

【问题讨论】:

    标签: javascript node.js server


    【解决方案1】:

    好的!我知道现在发生了什么。
    是我的 VPN 导致了这个问题,它将响应标头中的连接字段从“keep-alive”更改为“close”!!!
    所以我现在又遇到了一个问题......

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-01
      • 2020-06-20
      • 1970-01-01
      • 1970-01-01
      • 2018-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多