【问题标题】:AngularJS application communcation with PHP file on XAMP LocalhostAngularJS 应用程序与 XAMPP 本地主机上的 PHP 文件通信
【发布时间】:2016-05-31 17:03:24
【问题描述】:

我已经遇到这个问题超过一天了,对此我束手无策!首先,我以前从未与AngularJS 合作过,虽然我可以看到好处,但学习曲线却很大。我正在尝试使用$httpd.post() 将来自Angular 应用程序的请求发送到php 文件,但每次我这样做时,我都会在控制台中收到以下错误:

XMLHttpRequest cannot load http://localhost/angular-service/index.php. Request header field Access-Control-Allow-Origin is not allowed by Access-Control-Allow-Headers in preflight response.

让我更详细地说。

Angular 应用程序在 Gulp server 上运行,PHP 文件托管在 XAMP localhost 上。 Gulp 正在端口 8080 上运行,XAMP 在端口 80 上运行。

我尝试通过转到httpd.conf 文件并在最底部添加以下内容来配置 XAMP 以启用 CORS 标头:

<Directory />
    Header set Access-Control-Allow-Origin "*"
    Header set Access-Control-Allow-Headers "Content-Type"
    Header set Access-Control-Allow-Methods "GET, PUT, OPTIONS, DELETE, POST"
</Directory>

很遗憾,这并没有产生任何影响。

我的angular 应用程序中发出请求的代码块在这里:

 $scope.getSomething = function () {       
     $http({
          method: "POST",
          url: "http://localhost/angular-service/index.php",
          data: "",
          headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).
        success(function(response) {
            if(response==1){
               console.log(response);
            }
        }).
        error(function(response){
            console.log(response);
        });
    }

PHP 文件在这里:

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
echo "I'm a PHP File";

谁能指出我需要做些什么来解决这个问题的正确方向。真是令人沮丧!

【问题讨论】:

    标签: php angularjs apache cors


    【解决方案1】:

    我建议您也将请求方法添加到您的 PHP 文件中。 这是一个例子:

    <?php
       header("Access-Control-Allow-Origin: http://yourdomain");
    
       /* Allowed request method */
       header("Access-Control-Allow-Methods: PUT");
    
       /* Allowed custom header */
       header("Access-Control-Allow-Headers: Content-Type");
    
       /* Age set to 1 day to improve speed caching */
       header("Access-Control-Max-Age: 86400");
    
       /* Options request exits before the page is completely loaded */ 
       if (strtolower($_SERVER['REQUEST_METHOD']) == 'options') 
       {
          exit();
       }
    
       /* Response data */ 
       $arr = array("user_name" => "tizen", "phone_number" => "12312334234");   
    
       /* Response data returned in JSON format */
       echo json_encode($arr);
    ?>
    

    更多关于 CORS 协议的信息请见here

    【讨论】:

    • 仍然得到相同的结果 Matheno
    • 我添加了一个 URL,其中包含有关 CORS 协议的更多信息。我建议你读一下。 :)
    【解决方案2】:

    尝试将此添加到您的.htaccess

    Header set Access-Control-Allow-Origin "*"

    当我遇到 PHPAngularjs 的相同问题时,这很有帮助..

    【讨论】:

      猜你喜欢
      • 2011-08-12
      • 2012-08-17
      • 1970-01-01
      • 1970-01-01
      • 2020-04-26
      • 2014-05-31
      • 1970-01-01
      • 1970-01-01
      • 2014-09-12
      相关资源
      最近更新 更多