zoro.cut zoro.cut - 8 months ago 422
reST (reStructuredText) Question

CORS header 'Access-Control-Allow-OrigCross-Origin Request Blocked yii2

I'm using yii2 rest api.
I want to get my information by ajax but I'm getting this error.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://........... (Reason: CORS header 'Access-Control-Allow-Origin' missing).

How can I fix this problem?


You should read this : Cors filter and REST Api and CORS filter

Cross-origin resource sharing CORS is a mechanism that allows many resources on a Web page to be requested from another domain outside the domain the resource originated from. In particular, JavaScript's AJAX calls can use the XMLHttpRequest mechanism.

The CORS filter should be defined before Authentication / Authorization filters to make sure the CORS headers will always be sent.

use yii\filters\Cors;
use yii\helpers\ArrayHelper;

public function behaviors()
    return ArrayHelper::merge([
            'class' => Cors::className(),
    ], parent::behaviors());