在 nodejs 中呈现网页时永不结束加载图标
Never ending loading icon when rendering a web page in nodejs
以下代码来自一个学术例子,其目的是加载一个存在于文件系统中的页面:
const sendErrorResponse = res => {
res.writeHead(httpStatus.NOT_FOUND, {"Content-Type": "text/html"});
res.write("<h1>FILE NOT FOUND</h1>");
res.end();
};
const customReadFile = (file_path, res) => {
if (fs.existsSync(file_path)){
fs.readFile(file_path, (error, data) => {
if (error) {
sendErrorResponse(res);
return;
}
res.write(data);
res.end;
})
} else {
sendErrorResponse(res)
}
};
const port = 3000,
http = require("http"),
httpStatus = require("http-status-codes"),
fs = require("fs");
http.createServer((req, res)=> {
let url = req.url;
console.log(`Requested url: ${url}`);
if (url.indexOf(".html") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/html"});
customReadFile(`./views${url}`, res);
} else if (url.indexOf(".js") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/javascript"});
customReadFile(`./public/js${url}`, res);
} else if (url.indexOf(".css") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/css"});
customReadFile(`./public/css${url}`, res);
} else if (url.indexOf(".png") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "image/png"});
customReadFile(`./public/images${url}`, res);
} else {
sendErrorResponse(res);
}
})
.listen(port);
console.log(`The server has started and is listening on port: ${port}`);
问题是在浏览器中呈现页面时(chrome),选项卡中的加载图标一直在刷新,就像在等待资源一样。
你能告诉我,这是什么原因造成的吗?
在 customReadFile
函数中你没有调用 res.end
,只需添加 ()
来修复它。
以下代码来自一个学术例子,其目的是加载一个存在于文件系统中的页面:
const sendErrorResponse = res => {
res.writeHead(httpStatus.NOT_FOUND, {"Content-Type": "text/html"});
res.write("<h1>FILE NOT FOUND</h1>");
res.end();
};
const customReadFile = (file_path, res) => {
if (fs.existsSync(file_path)){
fs.readFile(file_path, (error, data) => {
if (error) {
sendErrorResponse(res);
return;
}
res.write(data);
res.end;
})
} else {
sendErrorResponse(res)
}
};
const port = 3000,
http = require("http"),
httpStatus = require("http-status-codes"),
fs = require("fs");
http.createServer((req, res)=> {
let url = req.url;
console.log(`Requested url: ${url}`);
if (url.indexOf(".html") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/html"});
customReadFile(`./views${url}`, res);
} else if (url.indexOf(".js") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/javascript"});
customReadFile(`./public/js${url}`, res);
} else if (url.indexOf(".css") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "text/css"});
customReadFile(`./public/css${url}`, res);
} else if (url.indexOf(".png") !== -1) {
res.writeHead(httpStatus.OK, {"Content-Type": "image/png"});
customReadFile(`./public/images${url}`, res);
} else {
sendErrorResponse(res);
}
})
.listen(port);
console.log(`The server has started and is listening on port: ${port}`);
问题是在浏览器中呈现页面时(chrome),选项卡中的加载图标一直在刷新,就像在等待资源一样。
你能告诉我,这是什么原因造成的吗?
在 customReadFile
函数中你没有调用 res.end
,只需添加 ()
来修复它。