0

I cant seem to understand why the request is not sent as a POST request My code in NG2 is as follows:

let headers = new Headers({ 'Content-Type': 'application/json'}); let options = new RequestOptions({ headers: headers , method:RequestMethod.Post }); let content = [ { email:email, password: pass } ]; return this._http.post(this._apiPath, content, options).toPromise() .then(this.extractData) .catch(this.handleErrorPromise);

(I have coded it using the sample from: http://www.concretepage.com/angular-2/angular-2-http-post-example#example )

within my PHP server i receive the following request:

[15/May/2017:15:09:32 +0000] "OPTIONS /index.php/api/login HTTP/1.1" 404 90 "http://localhost:4200/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36"

When i run a simple wget request i receive the following correct request in my PHP Server:

[15/May/2017:15:02:51 +0000] "POST /index.php/api/login HTTP/1.1" 200 96 "-" "Wget/1.15 (linux-gnu)" web_1 | 2017/05/15 15:02:51 [info] 15#15: *21 client 172.18.0.1 closed keepalive connection

here is the wget command i use:

wget --post-data "email=myemail@gmail.com&password=test" http://localhost/index.php/api/login

any ideas why does the NG2 doesnt send a POST request? Thanks.

user1322801
  • 751
  • 1
  • 7
  • 20

1 Answers1

3

This is because of HTTP access control (CORS).

You are witnessing whats called a preflighted request. And I would imagine it is happening because of your content-type being set to json.

An OPTIONS request pretty much asks the server if the client is allowed to make a request.

A request will be preflighted... (para-phrasing)

...If the Content-Type header has a value other than the following:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

You will need to handle this on your server.

Edit: Here is a pretty good SO answer on CORS and Preflighting

Community
  • 1
  • 1
Daniel Cooke
  • 1,131
  • 5
  • 18