【问题标题】:$http get method fails even with valid json from .Net WebApi in AngularJS$http get 方法即使在 AngularJS 中使用来自 .Net WebApi 的有效 json 也会失败
【发布时间】:2016-08-14 00:29:44
【问题描述】:

我收到一个有效的 JSON 请求,但只调用了 $http fail 方法。它在萤火虫中显示OK 200。视图也没有更新。新手尝试 AngularJS,所以有些东西可能太错误了:)

 $http.jsonp("http://localhost:51377/api/Books/1").success(function(data, status, headers, config) {
        alert("Suc");
        $scope.people = data;
    }).error(function(data, status, headers, config) {
        $scope.people = data;
        alert("fail");
    });         

这是 firebug 中的响应:

{"ID":1,"BookName":"ASP.Net"}   

同样失败:

[{"ID":1,"BookName":"ASP.Net"}] 

$http 调用中的状态码中得到 404。我正在使用jsonp 应该注意CORS?当我从某个地方读到。我的角度在 file:// 协议中

更新 1: 尝试从 VS 在 localhost 中启动我的角度。相同的结果

更新 2: 我添加了配置更改以在我的后端 .net webapi 中删除 CORS,现在它可以与以下代码一起使用,但上面使用 jsonp 的原始代码仍然失败

        $http({
        method: 'get',
        url: 'http://localhost:51377/api/Books/',
        responseType: "json"
    }).success(function (data, status, headers, config) {
        alert(data);
        console.log('Success: ' + data);
        $scope.people = data;
    }).error(function (data, status, headers, config) {
        console.log('Error: ' + data);
    });

【问题讨论】:

  • 你试过把 Angular 文件放入 http 协议吗?
  • 您是否尝试添加 ?callback=JSON_CALLBACK (请参阅下面的答案)?它在角度文档中。此外,这个 JSFiddle 表明它是必需的:jsfiddle.net/saarmstrong/hYACX/8/light
  • @MarkWatson 我会尝试并在这里更新。

标签: javascript .net angularjs json asp.net-web-api


【解决方案1】:

相信您需要在请求中添加回调参数:

$http.jsonp("http://localhost:51377/api/Books/1?callback=JSON_CALLBACK")

更多信息在这里:

https://docs.angularjs.org/api/ng/service/%24http#jsonp

另外,请参阅这个 JSFiddle(不是我的):

http://jsfiddle.net/saarmstrong/hYACX/8/light/

当您删除回调参数时,它会失败...

【讨论】:

    【解决方案2】:

    尝试仅使用“/api/Books/1”而不是“http://localhost:51377/api/Books/1

    【讨论】:

      猜你喜欢
      • 2016-05-17
      • 2022-11-06
      • 2019-08-09
      • 1970-01-01
      • 2015-06-03
      • 2017-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多