THis is the error log from browser console XMLHttpRequest cannot load http://domain.com/xx/xxxxxxxx. Response for preflight has invalid HTTP status code 404
This is the expected response as received in Postman
{
"status": "success",
"code": "E012",
"message": "Contact sent"
}
this is the request made from Angular 2
makeRequest(name, recipient) {
let body = JSON.stringify({
"name": name,
"recipient": recipient
});
let authToken = localStorage.getItem('token');
console.log(authToken);
let headers = new Headers({'Authorization': authToken , 'Content-Type': 'application/json'});
let options = new RequestOptions({headers: headers});
return this.http.post(url, body, options )
.map(res => res.json());
}
Here is the behaviors function in Yii2
public function behaviors()
{
$behaviors = parent::behaviors();
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
// restrict access to
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
// Allow only POST and PUT methods
'Access-Control-Request-Headers' => ['*'],
// Allow only headers 'X-Wsse'
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 86400,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => [],
],
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
Here is my UrlManager
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
'POST <version:[\w-]+>/sms' => '<version>/sms/send',
'POST <version:[\w-]+>/users/verify' => '<version>/user/verify',
'POST <version:[\w-]+>/bulk' => '<version>/routine/index',
'POST <version:[\w-]+>/contact' => '<version>/contact/index'],