错误 [ERR_STREAM_WRITE_AFTER_END]:结束后写入

代码说明:当用户访问特定的 url 时,我返回特定的 HTML 文件:


const http = require('http');

const fs = require('fs');


fs.readFile('./funkcionalnosti-streznika.html', function(err1, html1) {

    fs.readFile('./posebnosti.html', function(err2, html2) {

        if (err1 || err2) {

            throw new Error();

        }


        http.createServer(function(req, res) {

            if (req.url == '/funkcionalnosti-streznika') {

                res.write(html1);

                res.end();

            }

            if (req.url == '/posebnosti') {

                res.write(html2)

                res.end();

            } else {

                res.write('random');

                res.end();

            }

        }).listen(8080)

    })

});

在终端上,当我访问 localhost:8080/funkcionalnosti-streznika 时出现此错误:


events.js:288

      throw er; // Unhandled 'error' event

      ^


Error [ERR_STREAM_WRITE_AFTER_END]: write after end

    at write_ (_http_outgoing.js:637:17)

    at ServerResponse.write (_http_outgoing.js:629:15)

    at Server.<anonymous> (/*filelocation*/:19:21)

    at Server.emit (events.js:311:20)

    at parserOnIncoming (_http_server.js:784:12)

    at HTTPParser.parserOnHeadersComplete (_http_common.js:119:17)

Emitted 'error' event on ServerResponse instance at:

    at writeAfterEndNT (_http_outgoing.js:692:7)

    at processTicksAndRejections (internal/process/task_queues.js:85:21) {

  code: 'ERR_STREAM_WRITE_AFTER_END'

我认为当我过早关闭响应时会出现问题。我应该如何将其更改为异步?


慕森卡
浏览 1195回答 2
2回答

青春有我

你已经意识到问题所在了。让我们看一下这段代码:&nbsp; &nbsp; http.createServer(function(req, res) {&nbsp; &nbsp; &nbsp; &nbsp; if (req.url == '/funkcionalnosti-streznika') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.write(html1);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.end();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; if (req.url == '/posebnosti') {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.write(html2)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.end();&nbsp; &nbsp; &nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.write('random');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; res.end();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }).listen(8080)假设那req.url是 ' /funkcionalnosti-streznika'。发生什么了?它进入第一个 if、writeshtml1和 ends res。然后检查它'/posebnosti',但它是不同的,因为第一个if是真的。这意味着else分支将被执行,因此res.write('random');被调用,但res在第一个时已经关闭if。建议:http.createServer(function(req, res) {&nbsp; &nbsp; if (req.url == '/funkcionalnosti-streznika') {&nbsp; &nbsp; &nbsp; &nbsp; res.write(html1);&nbsp; &nbsp; &nbsp; &nbsp; res.end();&nbsp; &nbsp; }&nbsp; &nbsp; else if (req.url == '/posebnosti') {&nbsp; &nbsp; &nbsp; &nbsp; res.write(html2)&nbsp; &nbsp; &nbsp; &nbsp; res.end();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; &nbsp; res.write('random');&nbsp; &nbsp; &nbsp; &nbsp; res.end();&nbsp; &nbsp; }}).listen(8080)

千万里不及你

只需在每个 if 之后写 return,这将停止进一步执行代码。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript