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
})
Use
res.setHeader()