You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

访问localhost链接页面无内容,Node.js服务代码求助

问题排查与解决

你的代码核心问题是异步操作的执行顺序错误:fs.readFile是异步函数,它的回调函数会在文件读取完成后才执行,但你在调用fs.readFile之后立刻调用了res.end(),这会导致HTTP响应提前结束,此时文件内容还没来得及写入响应,所以页面显示空白。

修正后的代码

const http = require('http');
const fs = require('fs');
const port = 3000;

const server = http.createServer(function(req, res) {
    fs.readFile('home.html', function(err, data) {
        if (err) {
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.write('404: File not found');
            res.end();
        } else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.write(data);
            res.end();
        }
    });
});

server.listen(port, function(error) {
    if (error) {
        console.log(error);
    } else {
        console.log('Server is listening on port ' + port + ' at http://localhost:' + port);
    }
});

关键改动说明

  • 将res.end()移到fs.readFile的回调函数内部,确保只有在文件读取完成(或出错)后才结束响应
  • 出错时不仅设置404状态码,还返回明确的错误提示文本,同时匹配对应的Content-Type
  • 把res.writeHead(200)移到成功读取文件的分支里,避免出错时仍返回200状态码

额外注意事项

  • 确保home.html文件和你的Node.js代码文件在同一目录下,否则fs.readFile会找不到文件,触发404错误
  • 可以查看控制台输出的错误信息,帮助快速定位问题

内容的提问来源于stack exchange,提问作者Randomguy660

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 15:45:17