【发布时间】: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