将Content-type更改为"application/json"POST方法,RESTful API

use*_*913 25 angularjs

大家好我是AngularJS的新手,我需要你的帮助..

我只需要将我的json POST到API并收到正确的响应.

这是我的JSON,我不知道在哪里编码.

JSON

{ 
    "userId"      :"testAgent2",
    "token"       :"testAgent2",
    "terminalInfo":"test2",
    "forceLogin"  :"false"
}
Run Code Online (Sandbox Code Playgroud)

不确定如果我这样做的话.

CONTROLLER.JS

function UserLoginCtrl($scope, UserLoginResource) {
    //Save a new userLogin
    $scope.loginUser = function() {
        var loggedin = false;
        var uUsername = $scope.userUsername;
        var uPassword = $scope.userPassword;
        var uforcelogin = 'true';

        UserLoginResource.save();
    }
}
Run Code Online (Sandbox Code Playgroud)

SERVICES.JS

angular.module('UserLoginModule', ['ngResource'])
    .factory('UserLoginResource', function($resource, $http) {
        $http.defaults.useXDomain = true;
        delete $http.defaults.headers.common['X-Requested-With'];
        $http.defaults.headers.post["Content-Type"] = "application/json"; //NOT WORKING

        return $resource('http://123.123.123.123\\:1234/SOME/LOCATION/THERE', {}, {
            save: { 
                method:'POST', 
                headers: [{'Content-Type': 'application/json'}] 
            } //NOT WORKING EITHER
        });
    });
Run Code Online (Sandbox Code Playgroud)

INDEX.HTML

<html ng-app>

<head>
<script src="js/lib/angular/angular.js"></script>
<script src="js/lib/angular/angular-resource.js"></script>
</head>


<body ng-controller="UserLoginCtrl">

<form class="form-horizontal" name="form-horizontal" ng-submit="loginUser();">

<div class="button-login">

<!-- start: button-login -->
<button class="btn btn-primary" type="submit">Login</button>

</div>

</form>


</body>   


</html>
Run Code Online (Sandbox Code Playgroud)

希望你能帮我们这个..

我一直在收到像Unsupported Media Type这样的回复...我不知道还能做什么......

任何建议或意见都会很棒..谢谢!

小智 23

假设您能够使用一个更新的"不稳定"版本,更改标题的正确语法是.

app.factory('BarService', function ($resource) {
var BarService = $resource('/foo/api/bars/:id', {}, {    
    'delete': {
        method: 'DELETE',
        headers: {
            'Content-Type': 'application/json'
        }
    }
});
 return BarService;
});
Run Code Online (Sandbox Code Playgroud)

我发现$ resource服务是构建应用程序的一个非常强大的工具,并且已经成熟到一定程度,你不需要再回到$ http.再加上像模式这样的活跃记录非常方便.


Joh*_*uff 21

在Angular中发布JSON对象非常容易.您需要做的就是以下内容:

创建一个Javascript对象

我将使用您代码中的确切属性.

var postObject = new Object();
postObject.userId = "testAgent2";
postObject.token = "testAgent2";
postObject.terminalInfo = "test2";
postObject.forceLogin = "false";
Run Code Online (Sandbox Code Playgroud)

将对象发布到API

要将对象发布到API,您只需要一个简单的$ http.post函数.见下文:

$http.post("/path/to/api/", postObject).success(function(data){
    //Callback function here.
    //"data" is the response from the server.
});
Run Code Online (Sandbox Code Playgroud)

由于JSON是发布到API的默认方法,因此无需重置.有关详细信息,请参阅$ http快捷方式上的此链接.

关于您的代码,请尝试更改您的保存方法以包含此简单的post方法.