ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client

前端 未结 5 505
-上瘾入骨i
-上瘾入骨i 2020-12-02 18:41

I\'m facing this weird issue in NodeJS when using with Passport.js, Express and Mongoose. Basically, I get an error saying \"Cannot set headers after they are sent to the cl

5条回答
  •  再見小時候
    2020-12-02 18:58

    Sorry for the Late response, As per the mongoose documentation "Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. However, unlike promises, calling a query's .then() can execute the query multiple time"

    so to use promises

    mongoose.Promise = global.Promise //To use the native js promises
    

    Then

    var promise = Profile.findOne({ user: req.user.id }).exec()
    promise.then(function (profile){
        if (!profile) {
          throw new Error("User profile not found") //reject promise with error
        }
        return res.status(200).json(profile) //return user profile      
    }).catch(function (err){
        console.log(err); //User profile not found
        return res.status(404).json({ err.message }) //return your error msg
    })
    

    here is an nice article about switching out callbacks with promises in Mongoose

    and this answer on mongooses promise rejection handling Mongoose right promise rejection handling

提交回复
热议问题