使用 Node.js 設定新的 http 服務器
當你第一次啟動它時,它會在螢屏上顯示正確的 html 文本,但是當你移動到我的代碼中的其他鏈接時,即:localhost:5001/about,它在我的 IDE 控制臺中給我一個錯誤
events.js:377
throw er; // Unhandled 'error' event
^
Error [ERR_STREAM_WRITE_AFTER_END]: write after end
at new NodeError (internal/errors.js:322:7)
at writeAfterEnd (_http_outgoing.js:694:15)
at ServerResponse.end (_http_outgoing.js:815:7)
at Server.<anonymous> (/Users/angelo/Documents/coding/node/node-tutorial/app.js:11:7)
at Server.emit (events.js:400:28)
at parserOnIncoming (_http_server.js:900:12)
at HTTPParser.parserOnHeadersComplete (_http_common.js:127:17)
Emitted 'error' event on ServerResponse instance at:
at writeAfterEndNT (_http_outgoing.js:753:7)
at processTicksAndRejections (internal/process/task_queues.js:83:21) {
code: 'ERR_STREAM_WRITE_AFTER_END'
}
[nodemon] app crashed - waiting for file changes before starting...
應用程式.js
const http = require('http');
const PORT = 5001;
const server = http.createServer((req, res) => {
if(req.url === '/'){
res.end('Home Page')
}
if(req.url === '/about'){
res.end('About Page')
}
res.end('Error page')
})
server.listen(PORT, () => {
console.log(`Server is listening on port: ${PORT}`)
})
我一直在尋找“結束后寫入”錯誤的答案,但沒有看到這個特定代碼塊的這個特定問題
uj5u.com熱心網友回復:
正如評論中提到的,這是由于res.end被多次呼叫,最簡單的解決方案是return在每個之后res.end或調整您的條件:
const http = require('http');
const PORT = 5001;
const server = http.createServer((req, res) => {
if(req.url === '/'){
res.end('Home Page')
}
else if(req.url === '/about'){
res.end('About Page')
}
else {
res.end('Error page')
}
})
server.listen(PORT, () => {
console.log(`Server is listening on port: ${PORT}`)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343605.html
標籤:javascript html 节点.js 表达
