d0rf47
d0rf47

Reputation: 499

Put Method in API always receives empty request body

I have built a NodeJS Restful API and literally every single route except one is working. I have an Angular front end, using the httpClientModule to send requests.

When I try to make a put request for one specific item, the request is empty upon arriving in the server. I have 3 other routes making put requests and they all work fine. Can anyone explain what is happening here. I have looked at some of the other threads which discuss similar issues but none of the issues a the same as mine. I truly cannot grasp what is happening.

Here is some relevant code. Thanks in advance.

API method

router.put("/api/login/:_id", passport.authenticate("jwt", { session: false }), (req, res) => {
  console.log(req.body)
  User.findById(req.params._id)
    .then((user) => {
      bcrypt.compare(req.body.password, user.password).then((isMatched) => {
        if (isMatched) {
          User.findByIdAndUpdate(_id, { password: req.body.password })
            .then(() => {
              res.sendStatus(200);
            })
            .catch((err) => {
              console.log("Password update error" + err);
            });
        } else {
          res.status(400);
        }
      });
    })
    .catch((err) => {
      console.log("Password Update Error" + err);
      res.status(400);
    });
});

Angular Service method

newPassword(_id: any, password:any):Observable<any>
  {    
    return this.http.put(this.url+`/admin/api/login/${_id}`, password);
  }

Upvotes: 0

Views: 160

Answers (1)

E. Mancebo
E. Mancebo

Reputation: 754

what if you wrap the password body into an object on the request? Let's say:

newPassword(_id: any, password: any): Observable < any >
{
    return this.http.put(this.url + `/admin/api/login/${_id}`, {password});
}

This way the body contains a password attribute.

Upvotes: 1

Related Questions