【问题标题】:How to send file with fastify & nestjs?如何使用 fastify & nestjs 发送文件?
【发布时间】:2019-09-16 22:55:52
【问题描述】:

我有以下前端中间件:

export class FrontendMiddleware implements NestMiddleware {
    use(req: any, res: any, next: () => void) {
        const url = req.originalUrl;
        if (url.indexOf('rest') === 1) {
            next();
        } else if (allowedExt.filter(ext => url.indexOf(ext) > 0).length > 0) {
            res.sendFile(resolvePath(url));
        } else {
            res.sendFile(resolvePath('index.html'));
        }
    }
} 

在 express 上运行良好,但在 fastify 上,res.sendFileundefined,那么我该如何解决呢?

【问题讨论】:

  • 哦,毕竟对你没用,或者你为什么不接受?
  • reply.type 也未定义
  • 你用过res.type吗?

标签: javascript node.js typescript nestjs fastify


【解决方案1】:

您还可以将 index.html 存储在内存中并从中发送:

const bufferIndexHtml = fs.readFileSync('index.html')
res.type('text/html').send(bufferIndexHtml)

【讨论】:

    【解决方案2】:

    看看这个issuesendFile 在 fastify 中没有等效方法;您必须手动完成:

    const stream = fs.createReadStream(resolvePath('index.html'))
    res.type('text/html').send(stream)
    

    【讨论】:

      猜你喜欢
      • 2020-12-22
      • 2020-05-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-16
      • 1970-01-01
      • 2020-05-22
      • 2020-02-10
      • 2020-08-09
      相关资源
      最近更新 更多