Angular2 Http post 400

I have this service:

@Injectable()
export class HttpserviceService {
  baseUrl: string = "http://localhost:3000/";
  headers = new Headers({
    'accept': 'application/json'
  });

 post(url: string,  data: any): Observable<any> {

    //send post request
    return this.http.post(this.baseUrl+url, JSON.stringify(data))
      .map(this.extractData) //this works
      .catch(this.handleError); //this as well
  }
}

and when I subscribe to this method:

user: User = {
  username: "test",
  password: "12345"
}
authUrl: string = 'user/auth';
return this.http.post(this.authUrl, user)
  .subscribe(data => {
    //console.log(data);
  });

I get

Status Code: 400 Bad Request

What could be wrong?

When I request usage postman, everything works fine

enter image description here

+4
source share
1 answer

In the postman, I see that you have 1 heading. Which you do not send in angular

Try following, headers should go as third parameter

post(url: string,  data: any): Observable<any> {

    //send post request
    return this.http.post(this.baseUrl+url, JSON.stringify(data),  {headers: this.headers})
      .map(this.extractData) //this works
      .catch(this.handleError); //this as well
  }
+3
source

Source: https://habr.com/ru/post/1669388/


All Articles