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

时间:2018-06-26 15:00:07

标签: 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();

我该如何使用控制器或中间件来实现它。

1 个答案:

答案 0 :(得分:6)

The nestjs doc tells you, how to serve static files.简而言之,这是您的操作方式:

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

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

使用@Res批注可以使用Express Framework的sendFile方法

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

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


来源: