错误[ERR_STREAM_WRITE_AFTER_END]:结束后写入 [英] Error [ERR_STREAM_WRITE_AFTER_END]: write after end

查看:102
本文介绍了错误[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)
    })
});

在终端上访问本地主机: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'

当我过早关闭响应时,我认为存在I问题。我应该如何将其更改为异步?

推荐答案

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

    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)

这篇关于错误[ERR_STREAM_WRITE_AFTER_END]:结束后写入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆