简体   繁体   English

在 nodejs 中呈现 web 页面时永不结束加载图标

[英]Never ending loading icon when rendering a web page in nodejs

The following code comes from an academic example, its intention is to load a page that exists in the file system:下面的代码来自一个学术例子,它的目的是加载一个存在于文件系统中的页面:

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}`);

The issue is that when rendered the page in the browser (chrome), the loading icon in the tab keeps refreshing like waiting for a resource.问题是,当在浏览器(chrome)中呈现页面时,选项卡中的加载图标会像等待资源一样不断刷新。

永无止境的加载图标

Can you tell me, what is causing this?你能告诉我,这是什么原因造成的吗?

In customReadFile function you are not calling res.end , just add () to fix it.customReadFile function 你没有调用res.end ,只是添加()来修复它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM