Answer the question
In order to leave comments, you need to log in
How to set up CORS in yii2?
Good day. I've been fighting with cors on yii2 for a day now. Front in vue, back in Yii2. They are on different domains.
No matter what I do, all requests are blocked, even simple ones. On the main page, a GET call is made for textual information, roughly speaking the site name, description, etc. There is no authorization. Normal get request. Two requests are sent and the first one is OPTIONS. And it also receives the answer "Single source policy prohibits reading a remote resource ...". I generally understand how it works. The server at the first request says what headers it can accept. So no matter what headers and parameters I allow, not a single request passes.
Explain how to solve the problem please. In search of an answer, it seems that I reached the very bottom of Google and that I did not try anything helped. A thought creeps in, maybe I’m not looking for something at all ..
On a local network, this method works:
Answer the question
In order to leave comments, you need to log in
In the controller, you need to allow execution of OPTIONS requests
protected function verbs()
{
return [
'login' => ['POST', 'OPTIONS'],
];
}
public function behaviors()
{
$behaviors = parent::behaviors();
// remove authentication filter
$auth = $behaviors['authenticator'];
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
fetch(API_URL.SIGN_IN, {
method: 'POST',
mode: 'cors', // режим запроса
//credentials:'include',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(values)
}).then ...
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question