代码之家  ›  专栏  ›  技术社区  ›  Masoud92m

yii2 restful api:(原因:CORS头_访问控制允许源__秷丢失)

  •  -1
  • Masoud92m  · 技术社区  · 6 年前

    我想使用react with yii2 restful,我创建了这样一个用户控制器:

    <?php
    namespace app\controllers;
    use yii\rest\ActiveController;
    
    class UsersController extends ActiveController
    {
        public $modelClass = 'app\models\User';
    }
    

    当在浏览器中打开链接时,显示我的用户,当我想使用时 axios 在React中,我得到错误i浏览器控制台:

    Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost/rest/web/users. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
    

    但是当我检查的时候 network 在Firefox开发工具中,我发现AXIOS请求和IT状态为200,并正确接收响应。

    我试着用 behaviors 在我的控制器中运行,如下所示:

    public function behaviors()
    {
        return [
            'corsFilter' => [
                'class' => \yii\filters\Cors::className(),
                'cors' => [
                    'Origin' => ['*'],
                    'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                    'Access-Control-Request-Headers' => ['*'],
                ],
    
            ],
        ];
    }
    

    但得到错误

    无效参数“yii\base\invalidArgumentException Response Content 不能是数组。

    我怎么能解决这个问题?

    1 回复  |  直到 6 年前
        1
  •  1
  •   Muhammad Omer Aslam    6 年前

    根据 docs 你应该先取消设置 authenticator 筛选以添加 Cors 过滤,所以你的行为应该看起来像

    public function behaviors() {
        $behaviors = parent::behaviors();
    
        $auth=$behaviors['authenticator'];
    
        // remove authentication filter necessary because we need to 
        // add CORS filter and it should be added after the CORS
        unset($behaviors['authenticator']);
    
        // add CORS filter
        $behaviors['corsFilter'] = [
            'class' => '\yii\filters\Cors',
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
                'Access-Control-Request-Headers' => ['*'],
            ],
        ];
    
         // re-add authentication filter
        $behaviors['authenticator'] = $auth;
    
        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
        $behaviors['authenticator']['except'] = ['options'];
        return $behaviors;
    }
    

    通过添加 beforeAction 像下面

    public function beforeAction($action)
    {
        Yii::$app->response->format = Response::FORMAT_JSON;
        return true;
    }