首页 > 解决方案 > 使用 fs 模块更改 node.js 中的 html 页面文件

问题描述

我试图学习 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'
}

标签: javascripthtmlnode.jswebbackend

解决方案


如果是“/login” ,该函数res.end()可以被调用两次。q.pathname您需要使用 . 分隔每个请求处理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();
    });
}
};

推荐阅读