【问题标题】:Angular Js $http.get CORS issue - Working in JqueryAngular Js $http.get CORS 问题 - 在 Jquery 中工作
【发布时间】:2015-01-20 10:00:24
【问题描述】:

大家好,我是 angularjs 的新手,我只是将我的应用程序从 jquery 转换为 angular js。但是我在angular js中遇到了ajax请求的困难。我的这段代码在 jquery 中运行良好。

Angularjs 代码:

 links.serverurl = My Another Server Address which is defined another location
 $scope.submit = function () {

 console.log(this.formData);

 $http.get(links.serverUrl).success(function (response) {  
   console.log(response);
 });

JQuery 工作代码:

var url = "http://pbc.mydev786.com/";

$.get(url+"?"+data,function(response){
  $("div[data-role='page']").hide();
  $("#showbill").show();
  $(".billresult").html(response);
});

我的 PHP 标头:

 header('Access-Control-Allow-Origin: *');
 header('Access-Control-Allow-Methods: POST, GET, OPTIONS, PATCH, DELETE');  
 header('Access-Control-Allow-Headers: Origin, Content-Type,X-Requested-With');

AngularJs 配置:

$myapp.config(['$routeProvider', '$httpProvider', function ($routeProvider, $httpProvider) {
        $routeProvider
                .when('/', {templateUrl: "home.html"})
                .when('/electricity', {templateUrl: "electricity.html"})
                .when('/evo', {templateUrl: "evo.html"})
                .when('/ptcl', {templateUrl: "ptcl.html"})
                .when('/suigas', {templateUrl: "suigas.html"})
                .when('/iesco', {templateUrl: "iesco.html"})
                .when('/lesco', {templateUrl: "lesco.html"})
                .when('/fesco', {templateUrl: "fesco.html"})
                .when('/kesc', {templateUrl: "kesc.html"})
                .when('/extra', {templateUrl: "extra.html"})
                .when('/myaccount', {templateUrl: "myaccount.html"});
        $httpProvider.defaults.useXDomain = true;
        delete $httpProvider.defaults.headers.common['X-Requested-With'];
    }]);

请求的标头:

Accept  application/json, text/plain, */*
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Content-Length  20
Content-Type    text/plain; charset=UTF-8
Host    pbc.mydev786.com
Origin  http://localhost:8383
Referer http://localhost:8383/PakistanCheckBill/
User-Agent  Mozilla/5.0 (Windows NT 6.3; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0

响应标头:

Connection  keep-alive
Content-Encoding    gzip
Content-Type    text/html
Date    Tue, 20 Jan 2015 11:47:43 GMT
Server  nginx/1.6.2
Transfer-Encoding   chunked

【问题讨论】:

  • 对我不起作用,用更多代码编辑问题
  • 你会得到什么错误,如果有的话?服务器文件的响应是什么?
  • 跨域请求被阻止:同源策略不允许读取位于 [pbc.mydev786.com 的远程资源。这可以通过将资源移动到同一域或启用 CORS 来解决。
  • 您确定您的服务器使用所需的标头响应什么?

标签: php jquery ajax angularjs


【解决方案1】:

只有这对我有用,没有任何 angularjs 技巧帮助我

# CORS Headers 
<ifModule mod_headers.c>
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "X-Requested-With, content-type"
</ifModule>

我也尝试用 php 设置这些标头,但不知道为什么。

【讨论】:

  • 这是唯一对我有用的解决方案。在我的代码中修改标头导致错误:标头已发送。顺便说一句,jquery 工作正常,只有角度有问题。