Monday, 9 December 2019

Get image from external web URL and pass it to another using ExpressJS GET route

Hi all,As the title says, there is a web URL which responds with an image (example: https://api.discover.digitalglobe.com/show?id=104001001EBB2B00 ) and I have an ExpressJS API with a GET route which I wish to get the image from the original URL and send it as a response.I have created the route and can get the image but for some reason the response is not visible (see print screen attached), as if the returned image in the response is broken..In browser:https://preview.redd.it/c6m14j6n8l341.png?width=1716&format=png&auto=webp&s=84b188d180818ac175d523d3fb59c1b781d7c7afIn Postman:https://preview.redd.it/usm5tl9p8l341.png?width=1192&format=png&auto=webp&s=3e1fccddf0e1f1dbd3a01dec8132aa74158d924cBelow is the dirty way I tried to accomplish thisrouter.get('endpoint', async (req, res) => {const { id } = req.query;const https = require('https');`const options = {` `method: 'GET',` `headers: {` "content-type": "image/jpeg" `}` };const request = https.request('https://api.discover.digitalglobe.com/show?id=104001001EBB2B00', options, response => {`let imagedata = '';` response.setEncoding('binary');response.on('data', function(chunk){ `imagedata += chunk` `});` `response.on('end', function() {` `// console.log('imagedata: ', imagedata);` `res.setHeader('Content-Type', 'image/jpeg');` `res.writeHead(200);` `res.end(imagedata);` `});\`` }).on("error", e => {console.log("Got error: " + e.message, e);`});` request.end();});​Any ideas what is wrong ?​Many thanks!

Submitted December 09, 2019 at 10:58AM by Devtopia

No comments:

Post a Comment