$http-get方法即使使用AngularJS中.Net WebApi的有效json也会失败

$http get method fails even with valid json from .Net WebApi in AngularJS

本文关键字:json 有效 失败 WebApi 方法 http-get AngularJS Net      更新时间:2023-09-26

我得到了一个有效的JSON请求,但只调用了$http fail方法。它在firebug中显示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吗?当我在某处阅读时。我的角度在文件中://协议

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

更新-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);
    });

我认为您需要在请求中添加一个回调参数:

$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/

当您删除回调参数时,它将失败。。。

尽量只使用"/api/Books/1"而不是"http://localhost:51377/api/Books/1"