noufalcep
noufalcep

Reputation: 3536

Error when sending post in Angular 2

Angular 2 post request showing this error.

do_login(username: string,password: string): Observable<string> {
    let body = JSON.stringify({"username":username,"password":password});
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.loginUrl, body, options)
          .map((response) => {
            return response.json();
          }
    );
}

Get request working fine. and POST url working fine when calling on REST client

enter image description here

What is missing in my code. Thanks for your helps.

Upvotes: 2

Views: 743

Answers (2)

Thierry Templier
Thierry Templier

Reputation: 202196

It's because of CORS. You don't handle preflighted requests on the server side. This is what the 405 status code says:

405 Method Not Allowed A request method is not supported for the requested resource; for example, a GET request on a form which requires data to be presented via POST, or a PUT request on a read-only resource.

It works for GET methods because you're in the case of simple requests, not preflighted ones. It's typically a server side issue not a frontend / Angular2 one.

These articles could help you to understand what happens:

Upvotes: 1

cartant
cartant

Reputation: 58400

CORS is involved, as there is an OPTIONS request that precedes the POST request.

The server is not providing a valid response to the OPTIONS request - resulting the error you have listed above. You will need to investigate the CORS configuration of your server, as that's where to problem lies - not in the above code.

If the GET is working fine, you should look at the Access-Control-Allow-Methods configuration

Upvotes: 1

Related Questions