I have the error while running the command ionic serve. I am trying to call the api using post method.
I got the error:
Failed to load http://abc.localhost/api/auth/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:8101' is therefore not allowed access.
How can I overcome on this?
I have written the api's in YII2 framework in api module with below behaviour:
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['contentNegotiator'] = [
'class' => 'yii\filters\ContentNegotiator',
'formats' => [
'text/html' => Response::FORMAT_JSON,
'application/json' => Response::FORMAT_JSON,
'application/xml' => Response::FORMAT_XML,
],
];
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => true,
'Access-Control-Max-Age' => 86400,
'Access-Control-Allow-Origin' => ['*', 'http://abc.localhost/*', 'http://localhost:8101/*']
],
];
return $behaviors; }
And my ionic2 cordova api call script is:
loading.present();
console.log(this.singleton.apiGuestToken);
let headers = new Headers();
headers.append("Accept", 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Authorization', this.singleton.apiGuestToken);
headers.append('withCredentials', 'true');
headers.append('Access-Control-Allow-Origin', 'http://abc.localhost');
let options = new RequestOptions({ headers: headers });
console.log(options);
let paramsData = { 'userType': userType, 'email': this.email, 'password': this.password };
console.log(paramsData);
this.http.post('http://abc.localhost/api/auth/login', paramsData, options)
.map(res => res.json()) //this.singleton.apiUrl +
.subscribe(data => {
let resultData = JSON.parse(data['_body']);
console.log(resultData);
}, error => {
console.log(error);// Error getting the data
loading.dismiss();
});
Even, I can't see the post parameters and Authentication in the chrome inspect. Thanks in advance!
During development you can use CORS plugin for Google Chrome.