【问题标题】:Changing html page file within node.js using fs module使用 fs 模块更改 node.js 中的 html 页面文件
【发布时间】:2020-10-22 17:03:28
【问题描述】:

我试图学习 node.js 和后端的东西,但遇到了这个问题。任何人都可以帮忙吗? 这是我的代码。我正在尝试将 html 页面从 h1.html 更改为我得到的 h2.html (错误 [ERR_STREAM_WRITE_AFTER_END]:结束后写入)

var serverFunction = function (req, res) {

var q = url.parse(req.url, true);
var status = "";
var name = "";

if (q.pathname == "/login") {
    name = q.query["name"] + ":";
    fs.readFile('./h2.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.write(status);
        return res.end();
    });
}

if(q.pathname == "/send" && "msg" in q.query)
{
    var msg = q.query["msg"];
    SaveMsg(msg, name);
}

if (q.pathname == "/show") {
    res.writeHead(200, {'Content-Type': 'text/html'});
    GetMessages((result) => {res.end(result);} );
}

else {
    fs.readFile('./h1.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.write(status);
        return res.end();
    });
}

};

完整的错误文本:

events.js:287
      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 C:\Users\parsa\Desktop\T\s.js:55:17
    at FSReqCallback.readFileAfterClose [as oncomplete] 
(internal/fs/read_file_context.js:63:3)
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'
}

【问题讨论】:

  • 去掉res.end()之前的返回;
  • 也没有用。同样的错误。

标签: javascript html node.js web backend


【解决方案1】:

如果q.pathname 是“/login”,函数res.end() 可以被调用两次。 您需要使用else if 分隔每个请求处理。

var serverFunction = function (req, res) {

var q = url.parse(req.url, true);
var status = "";
var name = "";

if (q.pathname == "/login") {
    name = q.query["name"] + ":";
    fs.readFile('./h2.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.write(status);
        return res.end();
    });
}

else if(q.pathname == "/send" && "msg" in q.query)
{
    var msg = q.query["msg"];
    SaveMsg(msg, name);
}

else if (q.pathname == "/show") {
    res.writeHead(200, {'Content-Type': 'text/html'});
    GetMessages((result) => {res.end(result);} );
}

else {
    fs.readFile('./h1.html', function(err, data) {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.write(data);
        res.write(status);
        return res.end();
    });
}
};

【讨论】:

    猜你喜欢
    • 2016-08-12
    • 2012-03-26
    • 2011-09-30
    • 2017-02-20
    • 2015-10-29
    • 2013-08-08
    • 2014-02-18
    • 2018-07-02
    • 1970-01-01
    相关资源
    最近更新 更多