I write back-end with laravel. And try to call api from IONIC use @angular/http.
In back-end serer, I already add Access-Control-Allow-Origin in middleware and response.
Middleware.
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE')
->header('Access-Control-Allow-Credentials', true)
->header('Access-Control-Allow-Headers', 'Content-Type')
->header('Vary', 'Origin');
Response.
return response($data, 200)
->withHeaders([
'Content-Type' => 'application/json',
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE',
'Access-Control-Allow-Credentials' => true,
'Access-Control-Allow-Headers' => 'Content-Type',
'Vary' => 'Origin',
]);
IONIC
url: any = 'http://myurl.local/api/';
headers = new Headers(
{
'Accept' : 'application/json',
'Content-Type' : 'application/json',
'Access-Control-Request-Methods' : 'POST'
});
options = new RequestOptions({ headers: this.headers });
login(username, password) {
let data = JSON.stringify({
username : username,
password : password
});
let fullUrl = this.url+'login';
return new Promise((resolve, reject) => {
this.http.post(fullUrl, data, this.options)
.toPromise()
.then((response) =>
{
console.log('API Response : ', response);
resolve(response.json());
})
.catch((error) =>
{
console.error('API Error : ', error.toString());
reject(error.json());
});
});
}
When I call api with 'Content-Type' : 'application/json' it always response error.
XMLHttpRequest cannot load http://myurl.local/api/login. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
But if I change 'Content-Type' to 'application/x-www-form-urlencoded'. I didn't get any errors.
But when i try to see input $request->all(). Data i got is '{"username":"XXXXXXXXXX","password":"XXXXXXXXXX"}' => NULL.
With postman is fine. I really try a lot of way to solve this problem, But I can't.
What wrong?