[英]Changing html page file within node.js using fs module
I was trying to learn node.js and back-end stuff and got this problem.我试图学习 node.js 和后端的东西并遇到了这个问题。 Can anyone help?任何人都可以帮忙吗? This is my code.这是我的代码。 I am trying to change html page from h1.html to h2.html where I get (Error [ERR_STREAM_WRITE_AFTER_END]: write after end)我正在尝试将 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();
});
}
}; };
Full error text:完整的错误文本:
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'
}
The function res.end()
can be called twice if q.pathname
is "/login".如果q.pathname
为“/login”,则可以调用 function res.end()
两次。 You need to separate each request processing by using else if
.您需要使用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();
});
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.