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

use*_*378 5 node.js express nestjs

我正在尝试从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();
Run Code Online (Sandbox Code Playgroud)

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

Upv*_*ote 13

nestjs文档会告诉您如何提供静态文件。简而言之,这是您的操作方法:

在main.ts中指定资产的根目录

app.useStaticAssets(path.join(__dirname, '/../public'));
Run Code Online (Sandbox Code Playgroud)

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

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

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


资料来源: