繁体   English   中英

如何从请求有效载荷中将数据发布为json?

[英]How to post data as json from request payload?

这是我的代码示例,尽管我将方法设置为post,但它将Request方法设置为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);

这是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();
        }

请享用...!!!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM