Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to serve image (png) with node.js and express

Tags:

node.js

I've studied similar questions on SO but haven't found a solution to my problem... I've set up an express route to serve images but I can't get it to return an image from where it's stored. Notice I've included a statement to allow requests from any origin. What happens is that when I make a request to http://localhost:8080/images/x10.png the response I get is an empty image element with src="http://localhost:8080/images/x10.png instead of from http://ubuntubox.dev/images/x10.png, which is where the image is actually located and is the path I'm ultimately passing to the request method. What am I missing? Thanks.

app.get('/images/*', function(req, res, path){
  var imagePath = req.url,
      url = 'http://ubuntubox.dev' + imagePath;

  request(url, function(error, response, img) {
    if(!error && response.statusCode === 200) {
      res.header('Access-Control-Allow-Origin', '*');
      res.writeHead(200, {'Content-Type': 'image/png' });
      res.end(img, 'binary');
    } else if(response.statusCode === 404) {
      res.status(404);
      res.type('txt').send('oops');
    }
  });
}).listen(8080, '127.0.0.1');
like image 318
deluxe_247 Avatar asked Jan 31 '14 20:01

deluxe_247


People also ask

How do I upload an image using Express?

Open the local page http://127.0.0.1:2000/ to upload the images. Select an image to upload and click on "Upload Image" button. Here, you see that file is uploaded successfully. You can see the uploaded file in the "Uploads" folder.

How do I read a JPEG in node JS?

createServer(function (req, res) { res. writeHead(200, {'Content-Type': 'text/html'}); fs. readFile('image. jpg', function (err, data) { if (err) throw err; res.


1 Answers

I don't know if you still have this problem, but..

The solution for your problem is just putting a .pipe(res) and it will send the file to the response

app.get('/images/*', function(req, res, path){
  var imagePath = req.url,
      url = 'http://ubuntubox.dev' + imagePath;

  request(url).pipe(res);
}).listen(8080, '127.0.0.1');
like image 102
Sergio Marcelino Avatar answered Sep 22 '22 00:09

Sergio Marcelino