【发布时间】:2017-10-17 17:58:14
【问题描述】:
这是我的简单路线:
router.post('/getFile', async (ctx) => {
const fileName = `${ctx.request.body.file}.pdf`;
const file = fs.createReadStream(fileName); // This file might not exist.
file.on('error', (err) => {
ctx.response.status = 500; // This status code doesn't make it to client when there's an error.
});
ctx.response.type = 'application/pdf';
ctx.response.body = file;
});
这是我的客户端代码:
async function main() {
const request = {
method: 'POST',
body: JSON.stringify({ file: 'bad-file-name' }),
headers: {
'Content-Type': 'application/json',
'Accept': 'application/pdf'
}
};
const response = await fetch('/getFile', request);
if (!response.ok) {
console.log(response.status); // This is always 404 when I give a bad file name, even though I set it to 500 above. Why?
}
}
当我发送正确的文件名时一切都很好,但是为什么响应状态代码总是404,即使我在错误期间在我的服务器代码中将它设置为500?是不是在我的代码到达ctx.response.body = ... 时响应已经完成发送,在这种情况下.on('error') 中的代码没有做任何事情?
任何帮助将不胜感激。
【问题讨论】:
标签: javascript node.js http fetch koa