Home > Enterprise >  How to make nodejs server act like a proxy and get img from cloudinary then send it to browser
How to make nodejs server act like a proxy and get img from cloudinary then send it to browser

Time:03-20

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...">

CodePudding user response:

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);

CodePudding user response:

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);
  • Related