Koa的\`ctx.status\`没有发送给客户

JavaScript KoaJS

小胖Gil

2020-04-03

这是我的简单路线:

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')什么都没做?

任何帮助,将不胜感激。

第3948篇《Koa的\`ctx.status\`没有发送给客户》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

0个回答

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android