1

for storage space issues i cannot save images in server so i had to store it in cloudinary and for seo purposes I had to serve it from my domain not cloudinary's so i thought to get img files from cloudinary and send it directly to browser (to be served from my domain name ) what i am missing is converting the img file i got from cloudinary api into the right form so i can send it using response object in nodejs here is the code

app.get('/uploads/img/:imgName', (req, res) => {
    axios.get('https://res.cloudinary.com/dkhccaa25/image/upload/blog_img/${req.params.imgName}')
    .then(response => {
    console.log(response);
    /* how to convert response into the right format so it can be sent */
    //
    //
    //
})
.then (response => {
    /*converted response */
    res.sendFile(response)

  })
  .catch(error => {
    console.log(error);
  });

how I can be able to send the file from node server to browser so it can be displayed using <img src="img url...">

Andrew Naem
  • 162
  • 12

2 Answers2

0

You do not have to use res.sendFile, this will require saving it to the filesystem. Basically - accept the response and pass it directly with the correct content-type header send by the upstream response to the client.

Minimal example:


const express = require('express');
const axios = require('axios');
const app = express();

app.get('/', (req, res) => {
  axios.get('https://static.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg').then((axiosResp) => {
    res.header('content-type', axiosResp.headers['content-type']).send(axiosResp.data);
  });
});

app.listen(3000);
madflow
  • 7,718
  • 3
  • 39
  • 54
  • thanks dear for your answer , but unfortunately it didn't work as i expected, the rendered image in the browser is just a small square, the full image not rendered – Andrew Naem Mar 18 '22 at 23:26
0

finally the problem solved by editing on @madflow answer (thanks for him )

const express = require('express');
const axios = require('axios');
const app = express();

app.get('/', (req, res) => {
  axios.get('https://static.pexels.com/photos/45201/kitty-cat-kitten-pet-45201.jpeg', {responseType: 'stream'})
.then((axiosResp) => {
     res.set({
       'Content-Type': axiosResp.headers['content-type']
     })
     axiosResp.data.pipe(res)

  });
});

app.listen(3000);
Andrew Naem
  • 162
  • 12