T
T
Timur Khudiyev2021-02-10 18:07:51
Yii
Timur Khudiyev, 2021-02-10 18:07:51

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:

spoiler
6023f526163ba615425888.png


On the battlefield I tried this:
spoiler
6023f54a9ef29238056147.png

and a billion more variations of parameters.

Server request in Vue:
spoiler
6023f57c9e2f4352977865.png


Application here
Data that I want to receive at this address

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Valentine, 2021-02-18
@Tpona

In the controller, you need to allow execution of OPTIONS requests

protected function verbs()
{
    return [
        'login' => ['POST', 'OPTIONS'],
    ];
}

In the authenticator settings, if used, exclude 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;
}

Also, when sending a request from the client, you need to specify the request mode mode
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 question

Ask a Question

731 491 924 answers to any question