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

Node.js项目localhost无响应及ERR_STREAM_WRITE_AFTER_END报错求助

问题解决:Error [ERR_STREAM_WRITE_AFTER_END] 及相关疑问

错误原因与修复

你的代码中两个if语句未做流程阻断,导致请求/或/about时,第一个res.end()已经结束响应,但代码仍会执行到最后一个res.end(),尝试对已关闭的响应流重复写入,从而触发write after end错误。

修复方案1:添加return阻断后续执行

const http = require('http') 
const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.end('Welcome to our home page')
        return // 提前返回,避免执行后续代码
    }
    if (req.url === '/about') {
        res.end("Here is our short abt page")
        return // 提前返回
    }
    res.end(`
       <h1>OOps!</h1>
       <p>We can't seem to find the page you are looking for</p>
       <a href='/'>Go back home</a>
    `)
})

server.listen(2000)

修复方案2:改用if-else if结构

const http = require('http') 
const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.end('Welcome to our home page')
    } else if (req.url === '/about') {
        res.end("Here is our short abt page")
    } else {
        res.end(`
           <h1>OOps!</h1>
           <p>We can't seem to find the page you are looking for</p>
           <a href='/'>Go back home</a>
        `)
    }
})

server.listen(2000)

两种方式都能确保每个请求仅执行一次res.end(),避免重复结束响应流。

是否需要启动XAMPP的Apache服务?

不需要。你已经通过Node.js内置的http模块创建了独立的HTTP服务器,它直接监听2000端口处理请求。启动Apache完全没必要,甚至可能因端口冲突引发问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 08:35:23