如何从 Nest.js 提供资产并添加中间件来检测图像请求

how to serve assets from Nest.js and add middleware to detect image request

我正在尝试从 Nest.js 服务器提供图像并添加中间件来跟踪所有请求,但我唯一能让它工作的方法是使用 express

import { NestFactory } from '@nestjs/core';
import * as bodyParser from "body-parser";
import {AppModule} from "./app.module";
import * as path from "path";
import * as express from 'express';


async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(bodyParser.json({limit: '50mb'}));

  app.use(function(req, res, next){
    next();
  });
  //
  app.use('/api/track/',express.static(path.join(__dirname, '/public'))); //Serves resources from public folder
  app.use('/api/track/:img', function (req, res, next) {
    console.log('do something');
    next();
  });

  await app.listen(3333);
}

bootstrap();

如何使用控制器或中间件实现它?

The nestjs doc tells you, how to serve static files. 简而言之,您可以这样做:

指定你资产的根目录main.ts

app.useStaticAssets(path.join(__dirname, '/../public'));

使用@Res注解可以使用express框架的sendFile方法

@Get('track/:imgId')
test(@Param('imgId') imgId, @Res() res) {
  const imgPath = getImgPath(imgId);
  return res.sendFile(imgPath, { root: 'public' });
}

此解决方案假定您的 nestjs 安装在后台使用 express。


来源:

想在这里补充一点,请确保您使用的是:

const app = await NestFactory.create<NestExpressApplication>(AppModule);

而不是这个:

const app = await NestFactory.create(AppModule);

在您的 main.ts 文件中。

它对我有用。只需将此控制器注入应用程序模块即可。

import { Controller, Get, Req, Res } from '@nestjs/common';

@Controller('uploads')
export class ServeFilesController {
    @Get('products/images/:imageName')
    invoke(@Req() req, @Res() res) {
        return res.sendFile(req.path, { root: './' });
    }
}