This is a question widely found in the forum but without a clear answer.
The made is, in all the questions the Access-Control-Allow-Origin is present. My case comes where, in local development, I have the frontend using a port, the Yii2 API REST using another and the error raises with any query.
I already have implemented the CORS according with the documentation
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['contentNegotiator']['formats']['application/json'] = Response::FORMAT_JSON;
// remove auth filter before cors if you are using it
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// CORS
$behaviors['corsFilter'] = [
'class' => Cors::class,
'cors' => [
// restrict access to
'Origin' => ['*'],
// Allow all methods except options
'Access-Control-Request-Method' => ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'OPTIONS'],
// Allow only headers 'X-Wsse'
'Access-Control-Request-Headers' => ['*'],
// Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
'Access-Control-Allow-Credentials' => true,
// Allow OPTIONS caching
'Access-Control-Max-Age' => 3600,
// Allow the X-Pagination-Current-Page header to be exposed to the browser.
'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
],
];
$behaviors['authenticator'] = [
'class' => CompositeAuth::class,
'authMethods' => [
['class' => QueryParamAuth::class],
],
];
return $behaviors;
}
In the urlManager, in the controller rule I’m using, I set the except parameter to 'except' => ['delete', 'create', 'update', 'view', 'options'],
because I need only 2 paths defined in my controller, for instance login and logout, no more:
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/site',
'pluralize' => false,
'except' => ['delete', 'create', 'update', 'view'],
'extraPatterns' => [
'POST login' => 'login',
'OPTIONS login' => 'login',
'POST logout' => 'logout',
'OPTIONS logout' => 'logout',
]
],
But when I make the post to login I’m getting
I’m clueless with CORS with the frontend in another port. I think this will happen if I bring it to the server with different subdomains.