Yii2: How to allow CORS on non-restfull API
<p>I am working with a pre-built API (not restfull) on Yii2 Framework. It responds with JSON data and accepts requests depending on User type and credential token. Now I have to make an app that is on a different location (domain) which is causing CORS conflict.</p>

<p>My app is jQuery and I'm using <code>$.ajax</code> for data sending and receiving.
How can I avoid this CORS conflict and use the API over ajax?</p>

<p>Regards</p>

<p>UPDATE:</p>

<p>As IStranger told me in his answer I added the following code:</p>

<pre><code>public function behaviors()
{
    $behaviors = parent::behaviors();
    $behaviors['corsFilter'] = [
        'class' =&gt; \yii\filters\Cors::className(),
        'cors' =&gt; [
            'Origin'                           =&gt; "*",
            'Access-Control-Request-Method'    =&gt; ['POST', 'GET'],
            'Access-Control-Allow-Credentials' =&gt; true,
            'Access-Control-Max-Age'           =&gt; 3600,
        ],
    ];
    return $behaviors;
}
</code></pre>

<p>But I am still getting the error. There is a <code>beforeAction</code> in the code can that be a problem?</p>

<p>This is the RAW HEADER</p>

<p>Request:</p>

<pre><code>Host: domain.com
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64; rv:48.0) Gecko/20100101 Firefox/48.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Referer: http://localhost/main/main.html
Content-Length: 296
Origin: http://localhost
Connection: keep-alive
</code></pre>

<p>Response:</p>

<pre><code>Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: Keep-Alive
Content-Length: 101
Content-Type: application/json; charset=UTF-8
Date: Thu, 22 Sep 2016 17:23:48 GMT
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive: timeout=5, max=100
Pragma: no-cache
Server: Apache/2.4.17 (Win64) PHP/5.6.16
Set-Cookie: PHPSESSID=ph0b322gbq65m1f3m8fp9fphc0; path=/; HttpOnly
X-Powered-By: PHP/5.6.16
</code></pre>