不同作用域中的res.writeHead和res.end会出现错误



下面是我的代码:

const http = require('http');
const fs = require('fs');
http.createServer(testfunc)
.listen(3333);
function testfunc(req,res) {

if (req.method === 'GET'){
fs.readFile('index.html', function(err,data){

res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.write("Hi");


});
res.end();

};
};

当我向/发送get请求时,我收到了如下错误。你能告诉我出了什么问题吗。如果remove res.end((工作正常。但是写res.end((.有什么不对

events.js:292投掷者;//未处理的"错误"事件^

错误[ERR_STREAM_WRITE_AFTER_END]:结束后写入在write_(_http_outgoing.js:629:17(位于ServerResponse.write(_http_outgoing.js:621:15(位于C:\Users\C5218529\3D Objects\RestApi\node shop sql\server.js:12:8在FSReqCallback.readFileAfterClose[as oncomplete](internal/fs/read_file_config.js:63:3(上在上发出"error"事件ServerResponse实例位于:位于writeAfterEndNT(_http_outgoing.js:684:7(在processTicksAndRejections(internal/process/task_queues.js:85:21({代码:'ERR_STREAM_WRITE_AFTER_END'}

res.end((;应该在res.write("嗨"(之后;在回调函数fs.readFile((内部。因为回调函数稍后执行(res.write(,res.end((首先执行。

在调用res.end((语句后,我们无法写入响应。

fs.readFile('index.html', function(err,data){
// these callback statements will be executed later
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.write("Hi");
res.end();

});
// statements below will be executed immediately after fs.readFile as it is async

最新更新