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?
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:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With