Hssan Bouzlima
Hssan Bouzlima

Reputation: 93

Angular consumes express web api , bad request

My angular app consumes a nodejs webapi :

var header = {
        headers: new HttpHeaders()
          .set('Authorization',  `Bearer ${this.token}`)
      }


      var url="http://localhost:3000/user/deleteTodoFromUser/"+idUser+"/"+idTodo;
      return this.http.put(url,"",header); 

my api :

**router.put('/deleteTodoFromUser/:id/:idTodo', passport.authenticate('bearer'), (req, res) => {**

 User.findByIdAndUpdate(req.params.id,{ $pull:{todos:{$in:[req.params.idTodo]}}},{new:true},(err, usr) => {
       if (err) { 
            res.send(err);
        } 
        if(usr)
        {
        res.send(usr);
        }
        else
        {
            res.status(400).send("bad request");
        } 

**My api works properly in postman **

** CORS are enabled **

in angular doesn't, it returns 400 (bad request )

let params = new HttpParams();
params = params.append('id', idUser);
params = params.append('idTodo', idTodo);

this.http.put(url, "", { headers: headers, params: params });

when I add params parameter in the request , It becomes like that

http://localhost:3000/user/deleteTodoFromUser/?id=5dfa958e98710030207952cc&idTodo=5dfa976ea4ea1d31f8919ee5 

but the api waits the request like that :

http://localhost:3000/user/deleteTodoFromUser/5dfa958e98710030207952cc/5dfa976ea4ea1d31f8919ee5 

the difference is my api waits the request id without id?= and idTodo?= and I want it like that

Upvotes: 0

Views: 195

Answers (1)

ic_paty
ic_paty

Reputation: 432

400 Bad Request, Whatever the endpoint is expecting, it's not getting it. Seems that there is an issue while passing params to your API or the token value sent to your API is invalid.

This is another way to send parameters to your API instead of Appending them to the URL

const headers = new HttpHeaders()
          .set('Authorization',  `Bearer ${this.token}`);

let params = new HttpParams();
params = params.append('id', idUser);
params = params.append('idTodo', idTodo);

this.http.put(url, "", { headers: headers, params: params });

If it's not the case try to make a call using real parameters value and a valid token that works in Postman in order to detect the root cause of the error that you are getting.

Upvotes: 1

Related Questions