React 和 Yii2 连接错误 - 请求的资源上不存在 'Access-Control-Allow-Origin' header

React and Yii2 connection error - No 'Access-Control-Allow-Origin' header is present on the requested resource

我尝试了在互联网上找到的数百万个不同示例。

可是我还是做不到:(

这是我的 REST 控制器:

<?
namespace app\controllers\admiral_api;

use yii\rest\Controller;

class MainPageController extends Controller {

    public function actionIndex() {
        return 'test';
    }

}
?>

我发现我需要使用 Yii2 在服务器端通过 CORS 过滤器启用这个 'Access-Control-Allow-Origin'。而且不管我怎么试,还是不行。

在这种情况下,您有适合您的示例吗?谢谢!

您需要在Controller behaviors方法中添加Origin。

public function behaviors() {
        return [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    // restrict access to
                    'Origin' => (YII_ENV_PROD) ? [''] : ['http://localhost:3000', 'http://your.store.com'],
                    // Allow only POST and PUT methods
                    'Access-Control-Request-Method' => ['GET', 'HEAD', 'POST', 'PUT'],
                    // Allow only headers 'X-Wsse'
                    'Access-Control-Request-Headers' => ['X-Wsse', 'Content-Type'],
                    // 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'],
                ],
            ],
        ];
    }