Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 HTTP POST does an OPTIONS call

Tags:

angular

I'm encountering a really strange problem with my Angular 2 application. I actually want to make a POST call containing a JSON to my Play Scala API, but it keeps want to try to make an OPTIONS call.

Here is my code :

LoginService

constructor (private _apiEndpoint: ApiEndpoint) {}

postLogin(login: string, credential: string): Observable<AuthToken> {
    let headers = new Headers({ "Content-Type": "application/json" })
    let jsonLogin = {"login": login, "password": credential}

    return this._apiEndpoint.postLogin(JSON.stringify(jsonLogin), headers)
                    .map(this._apiEndpoint.extractData)
}

ApiEndpoint

constructor (private _http: Http) {}

postLogin(body: string, options: any) {
    return this._http.post("http://localhost:9000/login", body, {
        headers: options
    })
}

And then when I try to make the call (I've tried to console.log to check the JSON and it's correct), and the call tries to make an OPTIONS call for whatever reason :

Google request picture

Has anyone an idea ? Thanks !

like image 247
Guigui Avatar asked Aug 26 '16 08:08

Guigui


People also ask

What does HttpClient post return?

The HttpClient. post() returns Observable instance of given response type. On this page we will see injecting HttpClient , creating request body and passing HTTP options. We will also look into error handling. For the demo we will use Angular In-Memory Web API to post data.

What is post method in Angular?

post() method is an asynchronous method that performs an HTTP post request in Angular applications and returns an Observable. HttpClient. post() has a type parameter similar to the HttpClient. get() request, through which we can specify the expected type of the data from the server.

What does HTTP GET return in Angular?

get() method is an asynchronous method that performs an HTTP get request in Angular applications and returns an Observable. And that Observable emits the requested data when the response is received from the server.


1 Answers

You are making a cross domain request.

The request is to localhost:9000 and is made from localhost:9002.

The browser creates a pre-flight request with the OPTIONS verb in order to know if he can continue and make the "real" request.

Read more about CORS here.

like image 127
Amir Popovich Avatar answered Sep 20 '22 10:09

Amir Popovich