'res.set('Content-Type','image/jpg') is not working while serving image in node js

res.set('Content-Type', 'image/jpg') is not working while serving us files in node js. Please take a look at code what is wrong with this code. I am getting the User Value and avatar binary value from the database but not able to see it on the browser.

http://localhost:3000/users/5f8930bba34fd3166c1b3f72/avatar and I am hitting this URL on the local server

router.get('/users/:id/avatar', async (req,res)=>{
        try {
            const user= await User.findById(req.params.id)
            if (!user || user.avatar){
                throw new Error('Avatar not found !!')
            } 
            res.set('Content-Type','image/jpg')
            res.send(user.avatar)
        } catch (error) {
            res.status(404).send()
        }
    })

Below are my dependencies:

"dependencies": {
    "bcryptjs": "^2.4.3",
    "express": "^4.17.1",
    "jsonwebtoken": "^8.5.1",
    "mongodb": "^3.6.2",
    "mongoose": "^5.10.8",
    "mongoose-unique-validator": "^2.0.3",
    "multer": "^1.4.2",
    "validator": "^13.1.17"
  }

This is my user model

const userSchema=new mongoose.Schema({
    name:{
        type:String,
        required:true,
        trim:true,
        //unique:true,
    },
    age:{
        type:Number,
        default:0,
        validate(value){
            if(value<0){
                throw new Error('Age must be positive number')
            }
        }
    },
    email:{
        type:String,
        required:true,
        trim:true,
        unique:true,
        lowercase:true,
        validate(value){
            if(!validator.isEmail(value)){
                throw new Error('Email is invalid')
            }
        }
    },
    password:{
        type:String,
        required:true,
        minlength:7,
        trim:true,
        validate(value){
            if(value.toLowerCase().includes('password')){
                throw new Error('Password can not contain "password"');
            }
        }
    },

    tokens:[{
        token:{
            type:String,
            required:true
        }
    }],

    avatar:{
        type:Buffer
    }
    
},{
    timestamps:true
})


Solution 1:[1]

Use res.setHeader()

res.setHeader('content-type', 'image/jpg');

Solution 2:[2]

No relation between res.set('Content-Type', 'image/jpg') and showing picture on the browser.

First you should add avatar .. if you using postman make new request with Post avatar then you can able to see it in the browser.

Hint: you have an error in if condition it should be : if (!user || !user.avatar) instead of if (!user || user.avatar)

Solution 3:[3]

Instead of:

res.set('Content-Type', 'image/jpg')

Use:

res.contentType("image/jpg") 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 wangdev87
Solution 2 Caesar
Solution 3 Undo