4

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 that method:

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

I'm getting an

Status Code:400 Bad Request

What can be wrong?

When I request using postman everything works ok

enter image description here

8
  • Well, this could be a CORS issue, show us the stacktrace of the error in your angular app. Commented Feb 10, 2017 at 14:43
  • 1
    The server should send a proper error message explaining why your data is invalid. If it doesn't, it should at least log it. If it doesn't, you could debug it. My point being: check yur server. Also, you didn't post the complete client code, so we don't know what you're doing with the headers, and specifying the content type and calling JSON.stringify() is useless, since Angular does it for you when sending an object directly. Commented Feb 10, 2017 at 14:45
  • @camaron i.imgur.com/4muLKwM.png that's it Commented Feb 10, 2017 at 14:46
  • @gsiradze so where is content type in request??? Commented Feb 10, 2017 at 14:47
  • Well, for a start, you're sending JSON, but your content type is text/plain. Second you're not showing the content of the response. Commented Feb 10, 2017 at 14:48

1 Answer 1

3

In postman i see that you have 1 header. Which you are not sending in angular

Try following, headers should go as a 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
  }
Sign up to request clarification or add additional context in comments.

5 Comments

it's Content-Type application/json and I have that in code
I added that as header but result is same
@gsiradze you have only initialization of headers, but you are not sending them, see my update
I dont know who downvoted but your edited answer works. thanks a lot it took my 2 hours
@gsiradze It must work. As i said you were not sending headers :) dont forget to mark as resolved.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.