【问题标题】:CORS Not Working (SpringBoot, CodeIgniter)CORS 不工作(SpringBoot、CodeIgniter)
【发布时间】:2017-08-09 07:02:54
【问题描述】:

我目前正在开发一个使用 Google Maps API 的小型网络应用。 我几周以来一直在努力解决的问题是 CORS,我已经尝试了其他程序员经常建议的所有可能的事情(修改 .htaccess、httpd.conf ;添加标头('Access-Control-Allow-Origin: *' ); 到 php 和 ajax-request 等....) 但仍然收到一条错误消息,上面写着“请求的资源上不存在'Access-Control-Allow-Origin'标头。来源'http://localhost'是因此不允许访问”(另见screenshot with full error message

当我使用 Chrome 的“Allow-Control-Allow-Origin: *”插件时,一切正常,但这不是我满意的解决方案。

当我打开 DevTools 并查看我的 index.php 的标头时,似乎 CORS 标头在那里,但控制台一直说“Allow-Control-Allow-Origin”标头仍然丢失! https://i.stack.imgur.com/4G9tW.png

index.php:

<?php
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();
}
?>
<!DOCTYPE html>
<html ng-app="myApp">
<!-- tags and code... -->

javascript:

function getData(){
  var key = "....";
  var url = "https://maps.googleapis.com/maps/api/distancematrix/json?origins=" + $scope.origin + "&destinations=" + $scope.location.address + "|&mode=" + mode + "&key=" + key;

  $.ajax({
            url: url,
            dataType: 'JSON',
            jsonpCallback: 'callbackFnc',
            type: 'GET',
            async: false,
            crossDomain: true,
            success: function () { },
            failure: function () { },
            complete: function (data) {
                if (data.readyState == '4' && data.status == '200') {
                    console.log("SUCCESS");
                    console.log(data.responseJSON);
                    //do stuff
                }
                else {
                    console.log("FAIL");
                    console.log(data);
                }
            }
        });
}

CI控制器:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class My extends CI_Controller {

    function __construct() {
        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, PUT, DELETE");
        parent::__construct();
    }

    /**
     * Index Page for this controller.
     *
     * Maps to the following URL
     *      http://example.com/index.php/welcome
     *  - or -
     *      http://example.com/index.php/welcome/index
     *  - or -
     * Since this controller is set as the default controller in
     * config/routes.php, it's displayed at http://example.com/
     *
     * So any other public methods not prefixed with an underscore will
     * map to /index.php/welcome/<method_name>
     * @see https://codeigniter.com/user_guide/general/urls.html
     */
    public function index()
    {
        $this->load->helper('url'); 
        $this->load->view('index');
    }

    public function index_options() {
        return $this->response(NULL, REST_Controller::HTTP_OK);
    }

}

CodeIgnoterApp/application/.htaccess:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

<IfModule authz_core_module>
    Require all denied
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

CodeIgnoterApp/system/.htaccess:

<IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
</IfModule>

<IfModule authz_core_module>
    Require all denied
</IfModule>
<IfModule !authz_core_module>
    Deny from all
</IfModule>

到目前为止,我已经在我的 dekstop-PC 和笔记本电脑 (XAMPP) 上运行了这个项目。 我使用 Springboot(不久前)和 CodeIgniter(当前)作为后端。 我也有一个不使用 localhost/backend-server 的版本(当然使用 html 而不是 php),它没有任何 CORS 问题。

【问题讨论】:

    标签: javascript php apache cors


    【解决方案1】:

    https://i.stack.imgur.com/t23UZ.png 错误表示 https://maps.googleapis.com/maps/api 在其响应中未包含 Allow-Control-Allow-Origin 标头。

    所以这个问题与你如何配置你的 PHP 代码无关。您的代码没有将该请求的响应标头设置为 https://maps.googleapis.com/maps/api。其响应标头必须由 https://maps.googleapis.com/maps/api 自己设置,否则您需要通过代理发送请求,该代理将标头添加到浏览器最终看到的响应中。

    但无论如何,根本问题是 https://maps.googleapis.com/maps/api 不支持来自客户端 JavaScript 的请求,该请求以您的代码尝试使用它的方式在 Web 应用程序中运行。

    相反,您需要使用受支持的Google Maps JavaScript API,它的客户端代码与您尝试的不同。 sample for the Distance Matrix service 看起来更像这样:

    <script>
    var service = new google.maps.DistanceMatrixService;
    service.getDistanceMatrix({
      origins: [origin1, origin2],
      destinations: [destinationA, destinationB],
      travelMode: 'DRIVING',
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    },…
    </script>
    
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
    

    【讨论】:

      猜你喜欢
      • 2023-03-13
      • 2017-08-19
      • 2017-07-14
      • 2018-06-01
      • 2013-08-25
      • 2016-02-25
      • 2022-10-03
      • 2013-11-14
      • 2018-09-28
      相关资源
      最近更新 更多