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

1.6k views Asked by At

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
})
3

There are 3 answers

5
wangdev87 On

Use res.setHeader()

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

Instead of:

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

Use:

res.contentType("image/jpg") 
0
mostafa khedre On

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)