在 AngularJS 和 PHP 中允许 CORS

Posted

技术标签:

【中文标题】在 AngularJS 和 PHP 中允许 CORS【英文标题】:Allow CORS in AngualrJS and PHP 【发布时间】:2014-11-09 14:53:23 【问题描述】:

我正在将 AngualrJS 用于带有一些 php 的单页应用程序(MAMP PRO 作为开发环境。)

在 angular http get 请求中,我有 3rd 方 api 提供程序,它在 http 请求中返回 json。

当我提出请求时,我得到“请求的资源上没有 'Access-Control-Allow-Origin' 标头”。

基本上我现在被困在 CORS 中超过 8 小时!不知道如何让浏览器 (Chrome/FF) 覆盖 CORS 并发送 http 请求。

这里是 Controller.js 中的获取请求:

在 Angular js 中:

factory.fetchJson = function (filePath) 

        return $http.get(filePath)
            .success(function (data, status) 
                return data;
                console.log('Success Fetch JSON', status);
            ).error(function (data, status, headers, config) 
                console.log('Error Fetch JSON', status);
            );
 

在 angualrjs Controller.js 中设置为允许 CORS

myApp.config(['$httpProvider', function($httpProvider) 
    $httpProvider.defaults.useXDomain = true;
    $httpProvider.defaults.withCredentials = true;
    delete $httpProvider.defaults.headers.common["X-Requested-With"];
    $httpProvider.defaults.headers.common["Accept"] = "application/json";
    $httpProvider.defaults.headers.common["Content-Type"] = "application/json";


]);

在 index.php 标头中允许 CORS 的设置:

    <html>

<?php

    // Allow from any origin
    if (isset($_SERVER['HTTP_ORIGIN'])) 
        header("Access-Control-Allow-Origin: $_SERVER['HTTP_ORIGIN']");
        header('Access-Control-Allow-Credentials: true');
        header('Access-Control-Max-Age: 86400');    // cache for 1 day
    

    // Access-Control headers are received during OPTIONS requests
    if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') 

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
            header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

        if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
            header("Access-Control-Allow-Headers:        $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']");

        exit(0);
    

    echo "You have CORS!";

    ?>

我不追求 JSOP 或 MIM 代理。

救命!

【问题讨论】:

你应该看看这个。 ***.com/questions/8719276/cors-with-php-headers 【参考方案1】:

终于在 chrome 中安装了所有这些:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en-US 和 CORS 工作正常。

【讨论】:

以上是关于在 AngularJS 和 PHP 中允许 CORS的主要内容,如果未能解决你的问题,请参考以下文章

如何在[PHP]中允许跨域[重复]

如何在php中允许有限大小的文件上传?

php中允许的内存大小为33554432字节耗尽(尝试分配43148176字节)

php数组键中允许的字符?

在 CodeIgniter 中允许 URL 中的任何字符

输入标签内的 HTML 名称属性中允许使用哪些字符?