【问题标题】:How to allow CORS in Yii2?Yii2中如何允许CORS?
【发布时间】:2021-11-17 21:35:38
【问题描述】:

我有一个 JavaScript 前端,它向我的 PHP 后端请求纯文本。

它几乎可以正常工作,除了因为我遇到了 CORS 问题。如何在我的 PHP 代码中允许 CORS?

我的前端(JavaScript 和 jQuery):

$.ajax({
    type: 'GET',
    url: 'http://localhost:8080/',
})
.done(function(data) {
    console.log(data);
})
.fail(function() {
    alert("Oh, no. CORS error again.");
});

我的后端(PHP 和 Yii2):

$result = file_get_contents('http://m2m.exemys.com/...'); // This URL is a bit larger with more parameters.
var_dump($result); // Plain text. Just some characters.

【问题讨论】:

标签: php jquery yii2 cors localhost


【解决方案1】:

检查这个。 Yii2 带有开箱即用的 cors 过滤器。阅读文档以了解用法:https://www.yiiframework.com/doc/api/2.0/yii-filters-cors

【讨论】:

    【解决方案2】:

    Yii2 支持 CORS 处理,如 official documentation 所写。

    public function behaviors()
    {
        return [
            'corsFilter' => [
                'class' => \yii\filters\Cors::class,
            ],
        ];
    }
    

    或者,您可以尝试在 PHP 后端添加以下标头:

    <?php
    
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: *');
    

    如果不行,看看https://stackoverflow.com/a/9866124/11591212

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-31
      • 2018-03-02
      • 2019-12-30
      • 2017-03-22
      • 2021-10-23
      • 2023-03-30
      • 2015-10-08
      • 2017-12-22
      相关资源
      最近更新 更多