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

Node.js http服务搭建后Postman及浏览器请求无响应问题咨询

问题分析与修复方案

你的代码存在几个关键问题,直接导致请求一直处于加载状态:

1. 回调函数参数顺序颠倒

createServer的回调函数第一个参数是请求对象(req),第二个才是响应对象(res),你写反了参数顺序,导致后续操作的req和res都是错误的对象,无法正常处理请求和响应。

2. 请求URL匹配错误

判断req.url时缺少开头的斜杠,正确的路径应该是"/myapi/user"而非"myapi/user",否则无法匹配到目标接口。

3. 未处理不匹配的请求

当请求的URL或HTTP方法不匹配时,没有调用res.end()结束响应,导致请求一直处于挂起状态。

4. PORT未设置默认值

如果环境变量PORT未定义,PORT会变成undefined,服务器无法正常监听端口,需要补充默认值。


修复后的完整代码

import { createServer } from 'http'

// 补充默认端口,避免环境变量未定义的情况
const PORT = process.env.PORT || 3000

const users = [
    { id: 1, name: "Jim" },
    { id: 2, name: "Dwight" },
    { id: 3, name: "Michael" }
]

// 修正回调参数顺序:req在前,res在后
const server = createServer((req, res) => {
    if (req.url === "/myapi/user" && req.method === "GET") {
        res.setHeader('Content-Type', 'application/json')
        res.write(JSON.stringify(users))
        res.end()
    } else {
        // 处理不匹配的请求,返回404并结束响应
        res.writeHead(404, { 'Content-Type': 'text/plain' })
        res.write('404 Not Found')
        res.end()
    }
})

server.listen(PORT, () => {
    console.log(`Server running on port: ${PORT}`)
})

验证方式

启动服务器后,在Postman或浏览器中访问 http://localhost:3000/myapi/user(使用默认端口的情况),此时会正确返回JSON格式的用户数组,不会再出现请求挂起的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 13:40:09