大佬教程收集整理的这篇文章主要介绍了yii2 restful api :(原因:CORS标头“ Access-Control-Allow-Origin”缺失),大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
更新了答案,因为所实现的逻辑是允许每个请求都通过身份验证过滤器()。
有两件事需要改变
// 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;
}
}
我想将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' => ['*'],],];
}
但出现错误
我该如何解决?
以上是大佬教程为你收集整理的yii2 restful api :(原因:CORS标头“ Access-Control-Allow-Origin”缺失)全部内容,希望文章能够帮你解决yii2 restful api :(原因:CORS标头“ Access-Control-Allow-Origin”缺失)所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。