【问题标题】:Error [ERR_STREAM_WRITE_AFTER_END]: write after end错误 [ERR_STREAM_WRITE_AFTER_END]:结束后写入
【发布时间】:2020-06-28 01:14:49
【问题描述】:

代码说明:当用户访问特定的 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'

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

【问题讨论】:

标签: javascript node.js fs


【解决方案1】:

您已经意识到问题所在。我们来看看这段代码:

    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)

假设req.url 是'/funkcionalnosti-streznika'。发生什么了?它进入第一个 if,写入 html1 并结束 res。然后检查'/posebnosti',但它不同,因为第一个if 是真的。这意味着else 分支将被执行,因此res.write('random'); 被调用,但res 已经在第一个if 中关闭。建议:

http.createServer(function(req, res) {
    if (req.url == '/funkcionalnosti-streznika') {
        res.write(html1);
        res.end();
    }
    else if (req.url == '/posebnosti') {
        res.write(html2)
        res.end();
    } else {
        res.write('random');
        res.end();
    }
}).listen(8080)

【讨论】:

  • 我正在查看文档,但我仍然不明白: res.end() 方法是否仅表示消息已完成,还是实际上结束了请求?在上面的示例中是否还有其他使用它的方法,就像在 if 条件末尾使用“return”来忽略其他情况一样?
  • @MarcusCastanho 请阅读nodejs.org/api/… 基本上你结束写入可写。在上面的代码中,您可以删除所有 res.end() 行并将它们放在 if-else if-else 块之后,因为它在所有情况下都会被调用。 return 为函数赋值并停止执行。 res.end 表示写作的结束。如果有帮助,您可以使用return res.end();
猜你喜欢
  • 1970-01-01
  • 2021-12-15
  • 1970-01-01
  • 1970-01-01
  • 2020-06-30
  • 1970-01-01
  • 1970-01-01
  • 2017-01-08
  • 2018-09-23
相关资源
最近更新 更多