【问题标题】:Cross Domain Request with AngularJS doesn't work使用 AngularJS 的跨域请求不起作用
【发布时间】:2015-01-26 07:32:41
【问题描述】:

我需要使用 Angular 进行跨域请求,但出现错误

XMLHttpRequest cannot load http://machine_name_in_my_network:8082/GetAll. No

“Access-Control-Allow-Origin”标头出现在请求的 resource. Origin 'http://localhost:53379' is therefore not allowed 使用权。响应的 HTTP 状态代码为 500。

我看到了here 一个解决方案示例,但对我不起作用。

这是我的本地主机向我网络中的一台机器发出的请求,应该返回一个 JSON。

代码片段

//Controller 
function crmContatosCtrl($scope, apiService) {
    apiService.get('/GetAll').then(function (data) {
       $scope.contatos = data;
    });

然后来为我服务

function comWebApi_Service($http, $log) {
    return {
        get: function (url, data) {

            //return $http.jsonp(ApiURL + url)
            //    .success(function (data) {
            //        debugger;
            //    })
            //    .error(function (data) {
            //        debugger;
            //    });

            return $http.get(ApiURL + url, data).then(
                function (res) {                
                    return res.data;
                });
        },

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

【问题讨论】:

  • 您能否显示您在网络标签中看到的内容...响应??
  • @harish 出现 This request has no response data available.,错误为 500
  • 您不能简单地通过在客户端设置标头来启用 cors,您发出请求的服务器必须启用 CORS
  • 你能分享你在服务器端尝试过什么吗?你是怎么启用cors的?? cors 启用也是服务器端的决定...
  • 阅读here

标签: javascript angularjs


【解决方案1】:

您需要在服务器上启用 cors

例如全局初始化

    var cors = new EnableCorsAttribute("*", "*", "*");
    config.EnableCors(cors);

阅读更多关于它here...阅读部分Scope Rules for [EnableCors]

【讨论】:

    【解决方案2】:

    这是 服务器 端缺少的代码,而不是您的浏览器 AngularJS 代码。您确实不需要在最近的 angularjs 构建中需要这些行中的任何一条。这些都是基于过时的信息(它们不会破坏任何东西,它们只是不必要的并且基于过时的copypasta):

    $httpProvider.defaults.useXDomain = true;
    delete $httpProvider.defaults.headers.common['X-Requested-With'];
    

    您的服务器代码需要在其 HTTP 响应中添加必要的 CORS 标头,因此请要求维护者这样做或发布服务器端 sn-ps,我们可以提供帮助。

    【讨论】:

      猜你喜欢
      • 2015-04-15
      • 1970-01-01
      • 2016-03-15
      • 1970-01-01
      • 2014-04-18
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2023-03-17
      相关资源
      最近更新 更多