小编典典

yii2 restful api :(原因:CORS标头“ Access-Control-Allow-Origin”缺失)

reactjs

我想将React与Yii2 RESTful一起使用,我创建了一个用户控制器,如下所示:

<?php
namespace app\controllers;
use yii\rest\ActiveController;

class UsersController extends ActiveController
{
    public $modelClass = 'app\models\User';
}

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

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请求及其状态为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响应内容不能为数组。

我该如何解决?


阅读 559

收藏
2020-07-22

共1个答案

小编典典

更新资料

更新了答案,因为所实现的逻辑是允许每个请求都通过身份验证过滤器(
感谢@KalyanHalderRaaz指出错误)。

有两件事需要改变

  • 重新添加过滤器时,最好指定您使用的身份验证。更改下面的代码
    // re-add authentication filter
    

    $behaviors[‘authenticator’] = $auth;

以下,我正在使用BasicAuth例如。

    $behaviors['authenticator'] = [
    'class' => yii\filters\auth\HttpBasicAuth::class
];
  • 当添加一个beforeAction()dont时,不要忘记包装逻辑,if(parent::beforeAction($action))否则它将对每个请求进行身份验证,因为我们只是true在这里为每个请求返回,也不调用将触发过滤器的父级。

beforeAction()以下内容替换

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

}

只要确保您要覆盖findIdentityByAccessToken()用户身份模型中的


根据文档,您应该首先取消设置authenticator过滤器才能添加Cors过滤器,因此您的行为应类似于

public function behaviors() {
    $behaviors = parent::behaviors();

    // 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 of your choce
    $behaviors['authenticator'] = [
        'class' => yii\filters\auth\HttpBasicAuth::class
    ];

    // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
    $behaviors['authenticator']['except'] = ['options'];
    return $behaviors;
}

您可以通过添加beforeAction以下内容将响应格式设置为控制器内部的json

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

}
2020-07-22