javascript - CORS 不工作(SpringBoot、CodeIgniter)

标签 javascript php apache cors

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

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

当我打开 DevTools 并查看 index.php 的 header 时,似乎 CORS header 在那里,但控制台一直显示“Allow-Control-Allow-Origin” header 仍然丢失! /image/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 Controller :

<?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>

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

最佳答案

/image/t23UZ.png错误表明 https://maps.googleapis.com/maps/api 的响应中未包含 Allow-Control-Allow-Origin header 。

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

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

相反,您需要使用受支持的 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>

关于javascript - CORS 不工作(SpringBoot、CodeIgniter),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42862307/

相关文章:

javascript - 如何在 Phonegap 中使用 angularJs?

javascript - 无法读取 null 的属性 'innerHTML' (我正在使用 window.onload - 在本书演示文件中工作)

apache - 启动部署架构-在没有Apache的情况下运行Glassfish V3前奏

php - MySQL 选择 : Returning multiple columns based on a column value in the same table

apache - 在 Apache 2.2 中将 header 读入环境变量?

jquery - IE6 和 Apache Logs 的 Superfish 悬停问题

javascript - 复制/覆盖 javascript 的 console.log 函数

javascript - 让聊天机器人 (wit.ai) 回复它没有正确的答案

php - java.io.FileNotFoundException,但 php 文件存在

php - 未定义索引,syntaxerror.json.parse