以下代码来自一个学术示例,其目的是加载文件系统中存在的页面:

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)中呈现页面时,选项卡中的加载图标会像等待资源一样保持刷新.

never ending loading icon

你能告诉我是什么引起的吗?

推荐答案

customReadFile函数中,您不需要调用res.end,只需添加()即可修复它.

Javascript相关问答推荐

如何通过onClick为一组按钮分配功能;

IMDB使用 puppeteer 加载更多按钮(nodejs)

WebRTC关闭navigator. getUserMedia正确

有没有可能使滑动img动画以更快的速度连续?

如何将Openjphjs与next.js一起使用?

使用LocaleCompare()进行排序时,首先使用大写字母

JS—删除对象数组中对象的子对象

Ember.js 5.4更新会话存储时如何更新组件变量

Chart.js-显示值应该在其中的引用区域

JS:XML insertBefore插入元素

在HTML语言中调用外部JavaScript文件中的函数

Use Location位置成员在HashRouter内为空

将多个文本框中的输出合并到一个文本框中

顶点图使用组标签更新列之间的条宽

如何使用Cypress在IFRAME中打字

如何检测当前是否没有按下键盘上的键?

使用静态函数保存 node 前的钩子

Select 所有输入.值

如何让noWrap在嵌套在Alert/AlertTitle组件中的排版组件中工作?

JS:inline date子串.