![](/img/trans.png)
[英]Downloading a zip file with Node.js using fs and http module not working
[英]Changing html page file within node.js using fs module
我試圖學習 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'
}
如果q.pathname
為“/login”,則可以調用 function 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();
});
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.