Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node JS return image in rest api response [closed]

On the rest api call of get user information I want to return user information along with image. Can anyone please tell how to return the image along with the information in node js. Also how I can see the information returned in web client like postman.

like image 546
alihsyed23 Avatar asked Feb 04 '15 23:02

alihsyed23


1 Answers

If you want to send image as binary data, you can use the built in res.sendFile function.

If you want this image to only be available to the current user, you can use a authorization framework like passportjs or even high level frameworks such as huntjs with all things included.

Below is an example that checks that req.user exists and then sends either JSON with a link to the image or the image itself. If the image is small it may be better to send a base64 encoded version.

app.get('/info', function(req,res){
    if(req.user){
        res.status(200).json({
            'imageName':'some image',
            'imageUrl':'/someImageUrlOnlyForAuthorizedUsers.jpg'
        });
    } else {
        res.status(401).send('Authorization required!');
    }
});

app.get('/someImageUrlOnlyForAuthorizedUsers.jpg', function(req,res){
    if(req.user){
        res.sendFile('./mySecretImage.jpg');
    } else {
        res.status(401).send('Authorization required!');
    }
});
like image 180
vodolaz095 Avatar answered Sep 30 '22 13:09

vodolaz095