节点静态文件服务器,如何使响应在异步回调中工作?
Node static file server, how to make response work in async callback?
我写了这个函数,当我在我的节点服务器上收到请求时触发它,它工作得很好,它发回一个自动开始下载的文件。
function(req, res) {
// … other code …
try {
const fileContent = fs.readFileSync(fullPath, 'utf-8');
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Disposition': `attachment; filename="${fileName}"`,
});
res.end(fileContent);
} catch (err) {
res.writeHead(404);
res.end();
}
}
现在我想用 readFile
方法重写它,所以我尝试了这样的方法:
function(req, res) {
// … other code …
fs.readFile(fullPath, 'utf-8', function(err, data) {
if (err) {
res.writeHead(404);
res.end();
return;
}
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Disposition': `attachment; filename="${fileName}"`,
});
res.end(data);
});
}
但现在它总是 returns 404 错误,我认为该函数在响应准备好之前就退出了,所以它丢弃了为时已晚的响应?我怎样才能让它发挥作用?
请不要建议使用第三方库,因为这不是我要问的。我只想对本机模块执行此操作。
提前致谢。
using node 10.7.0
问题实际上出在代码的前面,我只是忘记在 if 语句中 return:
function onRequest(req, res) {
// … other code …
if (someCondition) {
functionOfTheOriginalPost(req, res);
return;
// ^-- This is the return that I forgot so it
// was jumping down in the "404" area
}
res.writeHead(404);
res.end();
}
http.createServer(onRequest).listen(3000);
感谢@Paul 让我思考并意识到错误。
我写了这个函数,当我在我的节点服务器上收到请求时触发它,它工作得很好,它发回一个自动开始下载的文件。
function(req, res) {
// … other code …
try {
const fileContent = fs.readFileSync(fullPath, 'utf-8');
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Disposition': `attachment; filename="${fileName}"`,
});
res.end(fileContent);
} catch (err) {
res.writeHead(404);
res.end();
}
}
现在我想用 readFile
方法重写它,所以我尝试了这样的方法:
function(req, res) {
// … other code …
fs.readFile(fullPath, 'utf-8', function(err, data) {
if (err) {
res.writeHead(404);
res.end();
return;
}
res.writeHead(200, {
'Content-Type': 'text/plain',
'Content-Disposition': `attachment; filename="${fileName}"`,
});
res.end(data);
});
}
但现在它总是 returns 404 错误,我认为该函数在响应准备好之前就退出了,所以它丢弃了为时已晚的响应?我怎样才能让它发挥作用?
请不要建议使用第三方库,因为这不是我要问的。我只想对本机模块执行此操作。
提前致谢。
using node 10.7.0
问题实际上出在代码的前面,我只是忘记在 if 语句中 return:
function onRequest(req, res) {
// … other code …
if (someCondition) {
functionOfTheOriginalPost(req, res);
return;
// ^-- This is the return that I forgot so it
// was jumping down in the "404" area
}
res.writeHead(404);
res.end();
}
http.createServer(onRequest).listen(3000);
感谢@Paul 让我思考并意识到错误。