Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

706
Visualizações
how to serve assets from Nest.js and add middleware to detect image request

I am trying to serve image from Nest.js server and add middleware to track all request but the only way I could make it work was with 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();

How can I implement it with using the controller or middleware?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The nestjs doc tells you, how to serve static files. In short, here is how you do it:

Specify root directory of your assets in you main.ts

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

Use the @Res annotation to be able to use the sendFile method of express framework

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

This solution assumes that your nestjs installation uses express under the hood.


Sources:

  • https://github.com/nestjs/nest/issues/402
  • https://docs.nestjs.com/techniques/mvc

Want to add a point here, please make sure you're using:

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

Instead of this:

const app = await NestFactory.create(AppModule);

in your main.ts file.

over 4 years ago · Santiago Trujillo Relatório

0

It worked for me. Just inject this controller into the application module.

 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: './' }); } }
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda