5

我有以下前端中间件:

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.sendFileis undefined,那么我该如何解决呢?

4

2 回答 2

14

看看这个问题sendFile在 fastify 中没有等效的方法;你必须手动完成:

const stream = fs.createReadStream(resolvePath('index.html'))
res.type('text/html').send(stream)
于 2019-04-27T20:41:42.070 回答
1

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

const bufferIndexHtml = fs.readFileSync('index.html')
res.type('text/html').send(bufferIndexHtml)
于 2019-11-20T10:30:57.113 回答