0

After a post request , an error is thrown

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client at ServerResponse.setHeader

FInd the code below :

router.post('/share', (req, res) => {
    const {userArray} = req.body

    userArray.map(userArray => 
    Share.findOne({ username: userArray.username }, (err, user) => {
        if (err) {
            console.log('share in router user.js post error: ', err)
        } 

        else if (user) {
            Share.update({ username: userArray.username}, {$push: { sharedPapers: userArray.sharedPaper  }, status: 1,name:userArray.name},
              function (error, success) {
                    if (error) {
                        res.json(error)
                        // console.log(error);
                    } else {
                        // res.json(user)
                        res.json(user)
                        // console.log("success");
                    }
                });
        }

        else {
            console.log(userArray.username,userArray.sharedPaper)
            const newShare = new Share({
                username: userArray.username,
                sharedPapers: userArray.sharedPaper,
                status:1

            })

            newShare.save((err, shareHistory) => {
                if (err) {return res.json(err)}
                else{res.json(shareHistory)}

            })
        }
    })

)

    })
ReNinja
  • 543
  • 2
  • 10
  • 27
  • 2
    You have functions with callbacks inside a `.map()`, which actually complete after/during your final call to `.save()` where you also use a `res.json()` response. In addition you basically cannot include a `res.json()` within a loop. You only get to call that once. See also `bulkWrite()` examples on [Update MongoDB field using value of another field](https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field) for how you actually should be issuing updates within a loop. And using `findOne()` before each operation is basically redundant – Neil Lunn Mar 22 '19 at 07:16
  • I can understand that looping causes this error .. but could you explain it more . – ReNinja Mar 22 '19 at 12:10

0 Answers0