我想在Yii2 RESTful中使用React,我创建了一个用户控制器,如下所示:
<?php
namespace app\controllers;
use yii\rest\ActiveController;
class UsersController extends ActiveController
{
public $modelClass = 'app\models\User';
}
当在浏览器中打开链接显示我的用户时,当我想在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
时,我发现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' => ['*'],
],
],
];
}
但是get错误
无效参数- yii\base\InvalidArgumentException响应内容不能是数组。
我该怎么解决这个问题呢?
发布于 2018-12-17 07:13:56
更新
更新了答案,因为实现的逻辑是允许每个请求绕过身份验证筛选器(感谢 指出了错误)。
有两件事需要改变
//重新添加鉴权过滤器$behaviors‘’authenticator‘= $auth;
对于下面的示例,我使用BasicAuth
。
$behaviors‘’authenticator‘= 'class’=> yii\ filters \auth\HttpBasicAuth::class;
beforeAction()
时,不要忘记将逻辑包装在if(parent::beforeAction($action))
中,否则它会验证每个请求,因为我们只是为每个请求返回true
,而不是调用触发过滤器的父级。将beforeAction()
替换为以下内容
公共函数beforeAction($action) { if (parent::beforeAction($action)) { \Yii::$app->response->format = Response::FORMAT_JSON;return true;} }
只需确保您覆盖了用户身份模型中的findIdentityByAccessToken()
根据docs的说法,您应该首先取消设置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;
}
}
发布于 2021-02-16 03:17:02
另一种可能的解决方案是定义一个虚拟主机。当我将API URL设置为http://localhost:8080/或http://127.0.0.1:8080/时,我遇到了类似的问题
通过在XAMMP中定义虚拟主机并将其映射到127.0.0.1,这个问题就解决了。
https://stackoverflow.com/questions/53807205
复制相似问题