I have a REST server for queries to a database running in PHP , which via GET can query various data in JSON format .
Previously there was a client on another server written in Javascript + JQuery , so I needed to use CORS to connect to said server. At that time it was only necessary to add the following lines to the PHP page:
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json");
I am now migrating the client to Angular2 , but it turns out that trying to connect to the same server rejects CORS requests.
In principle I think it's server side rather than client side, but why if it worked before now it stopped working for Angular2? .
Angular requests are of this type:
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let url = this.apiHost + '/servicios/';
return this.http.get(url, options).map(response => response.json());
The problem you are experiencing is because the CORS specification states that the following conditions must be met for simple requests :
The only accepted methods are:
GET
HEAD
POST
Aside from the headers set automatically by the user agent (eg
Connection
,User-Agent
, etc.), the only headers that are allowed to be set manually are:Accept
Accept-Language
Content-Language
Content-Type
The only allowed header values
Content-Type
are:application/x-www-form-urlencoded
multipart/form-data
text/plain
Applications developed with jQuery meet these conditions, but those developed with Angular do not, since it
$http
changes the headerContent-type
toapplication/json
:In Spanish:
So, at a minimum, you need to add this to your PHP code to allow such a change made by Angular:
Explicitly authorizing the header
Content-Type
can use any value beyond those initially allowed (application/x-www-form-urlencoded
,multipart/form-data
andtext/plain
).I update the problem was fixed by adding the following headers
Complete is like this:
Even so, I still don't understand what the problem really was, so that it works for a javascript + jquery and doesn't work for Angular 2 .