如何从请求有效负载发布数据作为json?

时间:2015-01-23 03:24:55

标签: javascript json angularjs

这是我的代码示例,虽然我将方法设置为post,但它会将Request Method设置为OPTIONS并且请求有效负载不会被设置。

我不确定这是CORS的一个问题,因为它正在使用Chrome插件,如Postman和Rest Console。我检查了服务器请求的两个工具是请求方法:post,Content-Type:applicaion / json和$ scope.data中的数据将被设置为请求有效负载。会是什么原因?

angular.module('httpExample', []).controller('FetchController', ['$scope', '$http', '$templateCache',
function($scope, $http, $templateCache) {
$scope.headers= {
                'Accept': '*/*',
                'Content-Type': 'application/json; charset=UTF-8'
            };
            $scope.method = 'POST';
            $scope.url = 'http://localhost:56652/reqresp.svc/json/post';
            $scope.data={"requests":[{"__type":"AuthenticateAndGetProsties:#LabOra.ProsteModul.ReqResp.Requests", "Authentication":{ "__type":"UserAuthentication:#LabOra.ProsteModul.ReqResp","Username":"xxx","Password":"yyyy" }}]};

            $scope.fetch = function() {
                $scope.code = null;
                $scope.response = null;

                $http({method: $scope.method, url: $scope.url,data: JSON.stringify($scope.data),headers:$scope.headers, cache: $templateCache}).
                    success(function(data,status) {
                        $scope.status = status;
                        //$scope.data =x2js.xml_str2json(data);
                        $scope.data =data;
                    }).
                    error(function( status) {
                        $scope.data = "Request failed";
                        $scope.status = status;
                    });
            };
        }]);
})(window.angular);

1 个答案:

答案 0 :(得分:0)

这是CORS问题,Agatha休息服务没有启用CORS。要在agatha中启用CORS,您需要做的是在global.asax.cs

中进行以下配置
        // enable CORS
        response.AddHeader("Access-Control-Allow-Origin", "*");
        response.AddHeader("X-Frame-Options", "ALLOW-FROM *");

        if (context.Request.HttpMethod == "OPTIONS")
        {
            response.AddHeader("Access-Control-Request-Method", "POST,GET,PUT,DELETE,OPTIONS");
            response.AddHeader("Access-Control-Allow-Headers", "Accept");
            response.AddHeader("Access-Control-Allow-Headers", "Authorization,Origin,X-Requested-With,Content-Type");
            response.AddHeader("Access-Control-Max-Age", "1728000");
            response.End();
        }

享受...!

相关问题