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

Node.js如何搭建运行localhost服务?代码运行异常问题求助

Node.js本地服务无法运行问题修复

错误点

  • 核心问题:未正确调用响应结束方法,代码中仅写了res.end没有加括号执行,属于方法调用遗漏。res.end是http响应对象的内置方法,必须主动调用才会终止当前请求响应流程,否则请求会一直处于等待状态,浏览器无法拿到完整返回内容。
  • 可选优化:缺少响应头配置,部分浏览器可能会出现内容乱码或者识别异常的问题,建议补充res.writeHead配置。

修正后完整代码

const http = require('http');

const server = http.createServer((req, res) => {
    if(req.url === '/') {
        // 配置响应状态码和内容类型,避免乱码
        res.writeHead(200, {'Content-Type': 'text/plain; charset=utf-8'});
        res.write('hello world!');
        res.end(); // 补充括号调用结束响应
    }
});
server.listen(8000);
console.log('Listening on port 8000');

验证方式

修改代码后重新执行脚本,打开浏览器访问http://localhost:8000即可正常看到输出内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 12:45:04