Here is my simple route:
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;
});
And here is my client code:
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?
}
}
Everything is fine when I send a proper file name, but why is the response status code always 404
even though I set it to 500
in my server code during error? Could it be that the response is already finished sending by the time my code reaches ctx.response.body = ...
in which case the code in the .on('error')
isn't doing anything?