Angularjs不会将JSON数据发布到REST API

时间:2015-04-25 15:46:06

标签: angularjs angularjs-http

我是AngularJS的新手。我试图将数据发布到本地服务器。以下是代码。

        var postObject = new Object();
        postObject.email = "emailtobesaved1";
        postObject.userData ="userDatatobeSaved";
        var s=JSON.stringify(postObject);

        $http({
            url: 'http://localhost:8080/people',
            dataType: 'json',
            method: 'POST',
            data: s,
            headers: {
                "Content-Type": "application/json"
            }
        }).success(function(response){
            $scope.response = response;
        }).error(function(error){
            $scope.error = error;
        });

此数据未发布。我错过了什么吗?我在服务器端激活了正确的CORS过滤器。服务器端是一个Spring启动应用程序。

提前致谢。

1 个答案:

答案 0 :(得分:2)

您不应将数据对象转换为字符串并将其发送。将其作为json对象本身发送

请尝试使用此代码:

var postObject = new Object();
    postObject.email = "emailtobesaved1";
    postObject.userData ="userDatatobeSaved";
    //var s=JSON.stringify(postObject);

    $http({
        url: 'http://localhost:8080/people',
        dataType: 'json',
        method: 'POST',
        data: postObject,
        headers: {
            "Content-Type": "application/json"
        }
    }).success(function(response){
        $scope.response = response;
    }).error(function(error){
        $scope.error = error;
    });