yii2 restful api:(原因:缺少 CORS 标头“Access-Control-Allow-Origin") [英] yii2 restful api: (Reason: CORS header ‘Access-Control-Allow-Origin’ missing)

查看:53
本文介绍了yii2 restful api:(原因:缺少 CORS 标头“Access-Control-Allow-Origin")的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 Yii2 RESTful 中使用 React,我创建了一个这样的用户控制器:

I want use React with Yii2 RESTful, i created a users controller like this:

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

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

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

when open link in browser show my users, when i want use axios in react, i get error i browser console:

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).

但是当我在 firefox 开发人员工具中检查 network 时,我发现 axios 请求和它的状态为 200 并正确接收响应.

but when i check network in firefox developer tools, i find axios request and it status in 200 and recievies the response correctly.

我尝试在我的控制器中使用 behaviors 函数,如下所示:

i try use behaviors function in my controllers, like this:

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' => ['*'],
            ],

        ],
    ];
}

但得到错误

Invalid Argument – yii\base\InvalidArgumentException 响应内容不能是数组.

Invalid Argument – yii\base\InvalidArgumentException Response content must not be an array.

我该如何解决这个问题?

how i can fix this?

推荐答案

更新

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

Updated the answer as the logic implemented was allowing every request to by pass the authentication filters (Thanks to @KalyanHalderRaaz for pointing out the bug).

有两件事要改变

  • 重新添加过滤器时,最好指定您使用的身份验证.修改下面的代码

  • When re-adding the filters it is better to specify which auth you are using. change the code below

// re-add authentication filter
$behaviors['authenticator'] = $auth;

以下,我使用 BasicAuth 为例.

to the following, i am using BasicAuth for example.

$behaviors['authenticator'] = [
    'class' => yii\filters\auth\HttpBasicAuth::class
];

  • 添加 beforeAction() 时不要忘记将逻辑包装在 if(parent::beforeAction($action)) 否则它会验证每个请求因为我们只是为这里的每个请求返回 true 并且也没有调用会触发过滤器的父级.

  • When adding a beforeAction() dont forget to wrap the logic in if(parent::beforeAction($action)) otherwise it would authenticate every request as we are just returning true for every request here and also not calling the parent which would trigger the filters.

    beforeAction() 替换为以下内容

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

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

    Just make sure you are overriding the findIdentityByAccessToken() in the User identity model

    根据 docs 你应该首先取消设置authenticator 过滤器以添加 Cors 过滤器,因此您的行为应该看起来像

    According to docs you should first unset the authenticator filter in order to add the Cors filter, so your behavior should look like

    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

    And you can set the response format to json inside your controller by adding the beforeAction like below

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

    这篇关于yii2 restful api:(原因:缺少 CORS 标头“Access-Control-Allow-Origin")的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    相关文章
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆