我正在嘗試為靜態站點創建路由,但是將 readFile() 放在 if 陳述句中會導致我的瀏覽器無限加載并且內容不會加載。我試圖在不使用 Express 或任何類似框架的情況下做到這一點。
這是我的代碼:
var http = require("http");
var fs = require("fs");
var url = require("url");
var path = require("path");
var server = http.createServer((req, res) => {
let parsedURL = url.parse(req.url, true);
let fPath = parsedURL.path;
if (fPath === "/") {
fPath = "/index.html";
}
file = path.join(__dirname, "/public" fPath);
if (fPath === "/index.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
} else if (fPath === "/information.html") {
fs.readFile(file, (err, data) => {
if (err) {
console.error(err);
res.end("An error has occured.");
} else {
res.end(data);
}
});
}
});
server.listen(8000);
uj5u.com熱心網友回復:
如果if (fPath === "/index.html") {匹配且fs.readFile有錯誤,則不發送回應。
對于"/information.html".
如果fPath不是其中任何一個,那么您將到達最后并且您不發送回應。
無休止的加載是由瀏覽器等待您從未發送的回應引起的。
您需要確保通過陳述句的每條路徑都呼叫或向瀏覽器發送回應的另一個函式。ifres.end
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/518633.html
