【发布时间】: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,一切都会按预期工作:
- 当我在浏览器中刷新/关闭当前选项卡时,控制台应该记录一个字符串
close。
但如果我使用相对 url,这些不会在控制台中输出。我想知道为什么会这样?
【问题讨论】:
标签: javascript node.js server