Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return an image to the client using Nest.js framework?

I am building an application, currently facing a problem I want to return an images which is stored in my server. I want to return image to React client, then it would be rendered in my component. But I can't figure out how to return the image itself. As far as I understand, I need to return image as JSON? But can't figure out how to do it in Nest.js framework.

like image 617
LuckyLuke Avatar asked Nov 03 '19 18:11

LuckyLuke


1 Answers

First you should have a service, to serve static files. You can achieve this with Nest.JS. For example, if your images are placed in a public folder, placed in the root of your project, simply you can serve it, by adding the following line to your main.ts file:

import { join } from 'path';
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use('/public', express.static(join(__dirname, '..', 'public'))); // <-
  await app.listen(3000);
}

Then for example you have cat.png placed in the public folder, and you want to send this in your response, you can send something like this:

{
   image: `${baseUrl}/public/cat.png`
}

For example for your local server, baseURL will be http://localhost:3000.
You can take a look at this article for more detailed explanations.

like image 101
Pooya Haratian Avatar answered Nov 06 '22 23:11

Pooya Haratian