XMLHttpRequest cannot load https://mipage.com/examplephp. Request
header field Content-Type is not allowed by
Access-Control-Allow-Headers in preflight response.
If I change $http.post to $http.get request the server response with
the JSON, so.. I think is not problem the CORS. Also I put a proxy in
the ionic project.
Explanation:
When you make an HTTP GET request from $http.get() passing params object they are appended in querystring, and because the request has no message body the angular httpProvider removes the Content-Type header of the request.
So, your $http.get params in querystring :
username=prueba123&password=prueba123
Otherwise for an HTTP POST request from $http.post() passing params object they are parsed in json and inserted in the message body of the request, then the httpProvider adds the http request header Content-Type: application/json.
So, your $http.post params in request message body:
{"username":"prueba123","password":"prueba123"}
This is done by default transformRequest function of the angular httpProvider
Somehow you're violating the CORS policy, then you have to configure your api web server or your api back-end to handle the violation of CORS policy, specifically your error is raised by the lack of content-type within Access-Control-Request-Headers response field.
Possible solution (in your specific case)
If you are running your application from a local with ionic framework, you need to configure the ionic.config.json file and add a proxy of the same address and port where its hosted your application, so you're not violating the CORS policy.
example:
{
"name": "example project",
"app_id": "11ffxxxx",
//etc etc..
"proxies": [
{
"path": "/api",
"proxyUrl": "http://192.168.1.152:9083/api"
}
]
}
finally in your angular application you will need to configure properly api endpoint when run from a local:
function obtenerSesion() {
debugger;
return $http.post("/api",
{params: {username: 'prueba123',password: 'prueba123'}}).then(function(response) {
canchas = response.data;
return canchas;
})
.catch(generarError);
}
I advise you to automate this process by using a javascript task runner (gulp, grunt)