Node js return image in api rest response

Otherwise, the api call to obtain user information I want to return user information along with the image. Can someone tell me how to return an image along with information in node js. Also, as I can see the information returned in the web client, for example the postman.

+4
source share
1 answer

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

If you want this image to be accessible only to the current user, you can use an authorization framework like passportjs or even a high level like huntjs with all things turned on.

Below is an example that checks that req.userexists, and then sends either JSONwith reference to the image or the image itself. If the image is small, it might be better to send base64 .

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!');
    }
});
+9
source

All Articles