我想将React与Yii2 RESTful一起使用,我创建了一个用户控制器,如下所示:
<?php namespace app\controllers; use yii\rest\ActiveController; class UsersController extends ActiveController { public $modelClass = 'app\models\User'; }
当浏览器中的打开链接显示我的用户时,当我想axios在React中使用时,出现错误,我在浏览器控制台中显示:
axios
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,并正确接收响应。
network
我尝试behaviors在控制器中使用功能,如下所示:
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响应内容不能为数组。
我该如何解决?
更新资料
更新了答案,因为所实现的逻辑是允许每个请求都通过身份验证过滤器( 感谢@KalyanHalderRaaz指出错误)。
@KalyanHalderRaaz
有两件事需要改变
// re-add authentication filter
$behaviors[‘authenticator’] = $auth;
以下,我正在使用BasicAuth例如。
BasicAuth
$behaviors['authenticator'] = [ 'class' => yii\filters\auth\HttpBasicAuth::class ];
beforeAction()
if(parent::beforeAction($action))
true
用beforeAction()以下内容替换
public function beforeAction($action) { if (parent::beforeAction($action)) { \Yii::$app->response->format = Response::FORMAT_JSON; return true; } }
只要确保您要覆盖findIdentityByAccessToken()用户身份模型中的
findIdentityByAccessToken()
根据文档,您应该首先取消设置authenticator过滤器才能添加Cors过滤器,因此您的行为应类似于
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
beforeAction