Yii和Vue2 CORS启用,服务器响应预检OPTIONS请求,并返回404错误

yacmzcpb  于 2022-11-09  发布在  其他
关注(0)|答案(2)|浏览(152)

我有两个典型的例子。
首先是Yii2由此而来:https://github.com/m-alfan/api-yii2-boilerplate
第二个是Vue2:https://github.com/cornflourblue/vue-vuex-registration-login-example
我首先在我的Apache2服务器上部署了http://basic.vue2域,客户端通过npm服务器在第二个域上运行。
问题是,当我发送POST请求时,我得到了404选项
https://ibb.co/r6ctBHr
https://ibb.co/0mmQ44m
https://ibb.co/BZM4d7Y

有人知道如何为Yii配置CORS吗?我试着在GuestController.php behaviors()中添加cors,但是失败了。

alen0pnh

alen0pnh1#

404可能是一个错误的urlManager规则或一个缺失,你从这里开始。

h4cxqtbf

h4cxqtbf2#

为yii配置CORS,请确保允许OPTIONS操作/动词。
另请参阅此处的文档:CORS config
即:

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

    $behaviors['corsFilter'] = [
        'class' => \yii\filters\Cors::className(),
        'cors' => [
            'Origin' => ['*'],
            'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
            'Access-Control-Request-Headers' => ['*'],
            'Access-Control-Allow-Methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
            'Allow' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
            'Access-Control-Allow-Credentials' => null,
            'Access-Control-Max-Age' => 86400,
            'Access-Control-Expose-Headers' => []
        ]

    ];
    return $behaviors;
}

相关问题