![](/img/trans.png)
[英]Express NodeJS Routing Error text/html is not text/event-stream
[英]Server Sent Events are not “text/event-stream”
我想將服務器發送事件 (SSE) 添加到我在 nodeJS (Express) 上運行的項目中。 作為開始,我使用了以下代碼: https://github.com/hnasr/javascript_playground/blob/master/server-sent-events/index.js 。 這個示例代碼在單獨運行時就像一個魅力,但是當我將代碼合並到我的(更大的)項目中時,我遇到了一些我無法解決的錯誤。 我希望你能幫助我。 我認為弄亂了路由文件夾中的代碼,不確定。
我使用帶有 express 的 NodeJs 作為我的服務器。 文件夾app.js
包含此代碼。
#Routing code
var router_price_24h_changes = require('./routes/24hours');
app.use('/24hours', router_price_24h_changes);
#>>>a lot of other (probably unnecessary code)<<<
#Added this
app.get("/24hours-events", (req,res) => {
res.setHeader("Content-Type", "text/event-stream");
send(res);
console.log("Stream")
})
let i = 0;
function send (res) {
console.log("send")
res.write("data: " + `hello!${i++}\n\n`);
setTimeout(() => send(res), 1000);
}
這就是我的routes-24hours.js
樣子:
var express = require('express');
var router = express.Router();
const fs = require('fs');
router.get('/', function(req, res, next) {
const myHtml = fs.readFileSync('./24hours.html', 'utf-8');
const changes = fs.readFileSync("./changes.json", 'utf-8');
const changes2 = fs.readFileSync("./changes2", 'utf-8');
res.send(myHtml.replace(/data/g, JSON.stringify(({changes ,changes2 }), null, 0)));
});
module.exports = router;
從我的 chrome 瀏覽器訪問24hours-events
網頁時,我輸入了這個
let sse = new EventSource("http://localhost:3000/24hours-events");
在控制台日志中,這是響應:
http://localhost:3000/24hours-events 404 (Not Found)
注意:我還沒有創建“24 小時事件”html 文件
在隔離的 SSE 測試版本中,我在其后添加了sse.onmessage = console.log
並記錄了服務器事件。
如果有不清楚的地方並且需要更多信息來回答這個問題,我會很高興收到您的來信。
app.get("http://localhost:3000/24hours", (req,res) => {
定義路由時,您應該只指定路徑,而不是完整的 URL:
app.get("/24hours", (req, res) => {
收到的 HTML 可能是 404 頁面。 (您應該查看您的網絡面板,或直接打開 http://localhost:3000/24hours 來確認。)
在 24hours.html 文件的元數據中,我添加了以下內容:
<meta http-equiv="Content-Type" content="text/event-stream" charset="utf-8" />
刪除它,這是不正確的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.