Node.js ERR_STREAM_WRITE_AFTER_END错误原因及解决方法
问题解决:Node.js HTTP服务器出现ERR_STREAM_WRITE_AFTER_END错误
问题现象
创建http1.js文件后,访问localhost:5000能正常返回内容,但访问localhost:5000/about时浏览器显示localhost拒绝连接,控制台抛出以下错误:
node:events:490 throw er; // Unhandled 'error' event ^ Error [ERR_STREAM_WRITE_AFTER_END]: write after end at new NodeError (node:internal/errors:399:5) at ServerResponse.end (node:_http_outgoing:1009:15) at Server.<anonymous> (c:\Users\Suresh\pratice_Tuotorial(JN)\.vscode\tempCodeRunnerFile.js:9:9) at Server.emit (node:events:512:28) at parserOnIncoming (node:_http_server:1086:12) at HTTPParser.parserOnHeadersComplete (node:_http_common:119:17) Emitted 'error' event on ServerResponse instance at: at emitErrorNt (node:_http_outgoing:849:9) at process.processTicksAndRejections (node:internal/process/task_queues:83:21) { code: 'ERR_STREAM_WRITE_AFTER_END' }
原代码
const http = require('http') const server = http.create Server((req, res) => { if (req.url === '/') { res.end('Welcome to our home page') } if (req.url === '/about') { res.end('Here is our short history') } res.end( `<h1>Oops!</h1> <p>We can't seem to find the page your are looking for</p> <a h ref ="/">Back home page</a>` ) }) server.listen(5000)
问题原因
- 重复调用
res.end():两个独立的if语句没有阻止后续代码执行,当请求匹配/或/about时,执行完对应res.end()后,代码仍会走到最后的res.end()。HTTP响应流在第一次res.end()后就会关闭,再次调用直接触发write after end错误,导致服务器进程崩溃,浏览器因此显示连接被拒绝。 - 语法小错误:
http.create Server存在空格,正确写法应为http.createServer。
解决办法
有两种修复方式,同时修正代码里的小问题:
方式1:使用if-else if-else结构
确保只有一个res.end()会被执行:
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 history') } else { res.end( `<h1>Oops!</h1> <p>We can't seem to find the page you are looking for</p> <a href="/">Back to home page</a>` ) } }) server.listen(5000)
方式2:在每个if块内添加return
执行完res.end()后直接返回,终止后续代码运行:
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 history') return } res.end( `<h1>Oops!</h1> <p>We can't seem to find the page you are looking for</p> <a href="/">Back to home page</a>` ) }) server.listen(5000)
额外修正了HTML里的h ref拼写错误(改为href)和your的语法错误(改为you)。
内容的提问来源于stack exchange,提问作者Vaishnavi
相关产品推荐
相关产品推荐

