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

使用JavaScript调用Node.js HTTP服务器时出现404错误

解决Node.js HTTP服务器fetch请求404问题

问题场景

搭建了一个简易Node.js HTTP服务器,浏览器访问http://localhost:8081完全正常,但使用fetch()调用时返回404错误,实际请求地址变为GET http://localhost/:8081?q=hi。

相关代码

前端JS代码

fetch(":8081/?q=hi")

Node.js服务器代码

const requestListener = function (req, res) {
  res.writeHead(200);
  res.end('Hello, World!');
}
const server = http.createServer(requestListener);
server.listen(8081);

错误原因

问题出在fetch()的URL写法上::8081/?q=hi不符合URL规范,浏览器会错误地将端口号8081解析为路径的一部分,导致请求地址变成http://localhost/:8081?q=hi——而你的服务器监听的是8081端口,这个错误URL没有匹配到任何服务器路由,因此返回404。

另外注意:你的Node.js代码缺少http模块引入,需要补上const http = require('http');才能正常运行。

修复方案

根据部署场景选择以下任意一种写法:

  1. 完整绝对路径(跨端口请求时用)
    如果前端页面和服务器运行在不同端口,需要指定完整服务器地址:

    fetch("http://localhost:8081/?q=hi")
    
  2. 相对路径(同端口服务时用)
    如果前端页面也通过8081端口提供服务(比如服务器同时托管静态页面),可以直接用相对路径:

    fetch("/?q=hi")
    

调试优化建议

可以在服务器代码中添加请求日志,实时查看请求路径快速排查问题:

const http = require('http');
const requestListener = function (req, res) {
  console.log(`收到请求路径:${req.url}`); // 打印请求路径
  res.writeHead(200);
  res.end('Hello, World!');
}
const server = http.createServer(requestListener);
server.listen(8081, () => {
  console.log('服务器已启动:http://localhost:8081');
});

验证

修改fetch()的URL后,重启服务器并发起请求,即可正常收到Hello, World!响应,404问题解决。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:55:15