简体   繁体   中英

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

使用res.setHeader()

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM