0

I am using node.js and the express framework to send a get request for an image by appending the image to the body using $('body').append('<img src="images/image.gif?34567">'). When I send the request, the console is logging GET /images/image.gif?34567 200 1.223 ms, but it won't run the functions inside of my router for the route to that image.

router.get('/images/*', function(req, res) {
    console.log('Accessed image folder...')
    var requestURL =  url.parse(req.url,true);

    //ATTEMPT to capture request
    if(requestURL.pathname == '/images/image.gif') {
        console.log("Fetching image...")
    }

});

I was also trying to use the specific route: router.get('/images/image.gif', function(req, res) {, and tried following this example.

How can I make the GET router work when requesting a specific image inside of the images directory?

Community
  • 1
  • 1
maudulus
  • 10,627
  • 10
  • 78
  • 117

2 Answers2

1
router.get('/images/:imageName', function(req, res) {
  var image = req.params['imageName'];
  res.header('Content-Type', "image/gif");
  fs.readFile(image, 'utf8', function(err, data){
    if(err){
      res.end(404);
    }
    res.send(data)    
  });
});

Just grab the image name as a parameter, set the content type (you could also do this dynamically based on the requested file extension, for simplicity I only set it to gif), then do an async file load for the image name and return it.

Alex Hill
  • 713
  • 1
  • 5
  • 13
  • thanks for your input, but I've run the code and also made a similar, more simple version. Oddly enough, the router will ONLY work if I use a false path name, in terms of giving me back anything for `image`, otherwise I just get the same `GET /images/image.gif?34567 200 1.223 ms` logging in the console. – maudulus Nov 03 '14 at 20:55
0

If you are trying to view a image from node server, then you have to use express static . The following code might help you.

var express=require('express'),
    app=express();

app.use("/pictures", lib.express.static("./assets/images"));

Here '/pictures' is the route to get image(e.g http:\localhost\pictures) and '/assets/images' is actual path foe image.

If you want to upload the image then you should use any upload module of node as per your requirement.

Asis Datta
  • 561
  • 3
  • 11