【问题标题】:Codeigniter 4 API with Angular : 'http://localhost:4200' has been blocked by CORS policy带有 Angular 的 Codeigniter 4 API:“http://localhost:4200”已被 CORS 策略阻止
【发布时间】:2021-10-08 22:02:30
【问题描述】:

老实说,我一直在努力尝试各种解决方案来克服由 Codeigniter API 控制器引起的这个问题,但遗憾的是仍未解决。

所以使用 angular 并且每当我尝试调用此 API 时:http://afma-cloud-api.synchronism.com/api/

我在控制台上收到 CORS 错误:

  Access to XMLHttpRequest at 'http://afma-cloud-api.synchronism.com/api/' from origin 
'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

我已经尝试了很多解决方案,比如使用下面的代码在 htaccess 文件中添加标题:

Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

另外,我尝试在我的 PHP 代码的每个部分中直接设置标题,但没有任何改变。

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

最后这是我的控制器代码:

namespace App\Controllers;



use App\Models\ApiModel;
use CodeIgniter\RESTful\ResourceController;
use CodeIgniter\API\ResponseTrait;
use CodeIgniter\Controller;
use CodeIgniter\HTTP\Response;


class Api extends BaseController
{

    protected $apiModel;
    protected $apiConfig;
    protected $curl;
    protected $pipelines;
    protected $tickets;
    protected $allTickets;
    protected $stages;

    public function __construct()
    {

        $this->apiConfig = new \Config\ApiConfig();
        $this->apiModel = new ApiModel();
        $this->curl = \Config\Services::curlrequest();
    }

    public function index()
    {
        return $this->response->setJSON( ['message' => 'Interne Api used For Afma Cloud'] );
    }

}

【问题讨论】:

  • 你能显示请求快照和 response 标头吗?
  • 感谢您的关注,但使用邮递员标头发送状态 200 似乎一切正常,并且允许跨域/方法,但在我必须在发送 JSON 数据集之前设置标头状态之前没有任何效果。

标签: php angular api cors codeigniter-4


【解决方案1】:

Fiiiiinnaly 发现它,经过大量研究,我发现我必须将标题状态设置为 200,瞧,它就像一个魅力。

For native PHP I used this : header("HTTP/1.1 200 OK");

对于 Codeigniter HTTP 响应服务,我使用了这个:

$this->response->setStatusCode(200);
$this->response->setStatusCode(200)->setJSON( ['message' => 'Interne Api used For Afma Cloud'] );

【讨论】:

    猜你喜欢
    • 2019-11-16
    • 2019-12-29
    • 2020-01-26
    • 2019-05-27
    • 1970-01-01
    • 2019-11-17
    • 2019-10-13
    • 2019-10-31
    • 2020-07-09
    相关资源
    最近更新 更多