AngularJS:允许跨域AJAX请求

时间:2015-11-29 17:10:29

标签: angularjs apache cross-domain wamp

我正在尝试从我的新Angular应用程序调用REST Web服务。发出请求时,我收到此错误:

  

XMLHttpRequest无法加载http://localhost:8080/WebService。没有   '访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost'因此不允许访问。

我发现这种情况正在发生,因为浏览器不允许这样的操作。

在StackOverflow中one of the solutions禁用了一些安全选项。我试过这样做但它没有工作,我得到了同样的错误。

然后another solution建议将项目移动到服务器。所以我将项目移动到WAMP中的www文件夹。它没有用,因为我需要激活headers_module,然后修改httpd.conf添加此内容:

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

所以我激活了模块并修改了一般配置文件(不能记住如何只是形成我的web项目)并重新启动WAMP。它仍然没有工作。

我唯一能想做的就是在Eclipse JEE中创建一个Web项目并在Tomcat服务器上运行它。但我真的不想这样做。

如何解决此问题?

编辑我也尝试将其添加到我的角应用中:

app.config([ '$httpProvider', function($httpProvider) {
    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
}]);

问题仍然存在。

1 个答案:

答案 0 :(得分:0)

在开发自己的Web应用程序时遇到了同样的问题。这是一个CORS问题。我通过它做了什么叫做JSONP(JSON-Padding)。这种方法完全忽略了CORS。幸运的是,angularjs $ html服务允许使用JSONP。

我将向您推荐angularjs文档的以下部分:https://docs.angularjs.org/api/ng/service/ $ http

JSONP的一个重要概念是回调,它实质上就是你将用JSON填充(JSONP中的&#39; P&#39;)。回调作为http请求中的参数传递。

这是一些示例代码,我在我的Web应用程序中使用

(我的php层隐藏了我的开发人员密钥并调用了第三方API):

$method = isset($_GET['method']) ? $_GET['method'] : '';

//Check for a callback, which is needed for JSONP
if(isset($_GET['callback'])){

    //Check which method is being called.
    //I use method to abstract out the long urls of api's
    if($method == 'get_data_a'){

        $url = 'https://some.api.url?api_key='.$key;
        $response = file_get_contents($url);

        //Pad the JSON response with a function named after the callback for JSONP
        //You're returning something that looks like
        //myCallbackName(myJSONString);
        echo $_GET['callback'] . '(' . $response . ')';

    }
    else if ($method == 'get_data_b'){
        ....
    }
}

(我的应用程序代码 - AngularJS)

//I reference my php layer for REST services ; callback=JSON_CALLBACK as per angularjs documentation
var url =  my_php_layer_url + '?method=get_data_a&callback=JSON_CALLBACK';

//Call webservice using angularjs $http and the shortcut method for JSONP
$http.jsonp(url)
    .success(function (result) {
        //do whatever you want with the result; the result is properly formatted JSON
    })
    .error(function (data, status) {
        //do whatever you want with the error
    });

希望这会对你有所帮助。