【问题标题】:Trouble getting CORS to work between CodeIgniter and React app无法让 CORS 在 CodeIgniter 和 React 应用程序之间工作
【发布时间】:2017-07-15 15:59:06
【问题描述】:

我无法让我的 React 应用程序与我在我的计算机上托管的 API 进行通信。我对 CodeIgniter 不太熟悉,因此假设这部分存在错误/误解是安全的。我尝试将header('Access-Control-Allow-Origin:*'); 添加到application/config/rest.php 以及其他一些文件的顶部。当我执行 api 请求时,显然首先发送了飞行前 OPTIONS 请求,如下所示:

Request Headers:
Host: localhost:8000
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:51.0) Gecko/20100101 Firefox/51.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: GET
Access-Control-Request-Headers: apikey
Origin: http://localhost:3000
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

Response Headers:
Access-Control-Allow-Origin: *
Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection: close
Content-Type: text/html; charset=UTF-8
Expires: Thu, 19 Nov 1981 08:52:00 GMT
Host: localhost:8000
Pragma: no-cache
Set-Cookie: ci_session=3ba4cibif5sdgtfjjopmokt8k2fc1c1j; expires=Fri, 24-Feb-2017 19:18:05 GMT; Max-Age=7200; path=/; HttpOnly
X-Powered-By: PHP/5.5.38

OPTIONS 响应为 200。在服务器上,API 为我尝试获取的资源提供种子,并以 200 响应(但是我的应用程序没有看到这个)。 react 前端看到并记录了一个超级无用的

Error: Network Error
Stack trace:
createError@http://localhost:3000/bundle.js line 4801 > eval:15:15
handleError@http://localhost:3000/bundle.js line 4789 > eval:87:14

错误,我的应用程序甚至从未发出过 GET 请求(根据 Firefox 的开发工具)。 OPTION 的响应数据完全为空。这是怎么回事?

【问题讨论】:

    标签: php codeigniter http reactjs cors


    【解决方案1】:

    原来我需要检查它是否是服务器上的预检请求,并做出适当的响应:

    header('Access-Control-Allow-Origin: *');
    header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
    $method = $_SERVER['REQUEST_METHOD'];
    if($method == "OPTIONS") {
        die();
    }
    

    然后我可以使用头部中的 api 键发出正常请求。

    来自https://stackoverflow.com/a/19310265/419194

    【讨论】:

      猜你喜欢
      • 2013-09-03
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 2012-02-11
      • 2012-11-19
      • 1970-01-01
      • 2015-06-16
      • 2012-03-05
      相关资源
      最近更新 更多