【问题标题】:change Content-type to "application/json" POST method, RESTful API将 Content-type 更改为“application/json” POST 方法,RESTful API
【发布时间】:2013-06-20 10:35:59
【问题描述】:

我是 AngularJS 的新手,我需要你的帮助。

我只需要将我的 json 发布到 API 并收到正确的响应。

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

JSON

{ 
    "userId"      :"testAgent2",
    "token"       :"testAgent2",
    "terminalInfo":"test2",
    "forceLogin"  :"false"
}

不知道我这样做是否正确。

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

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

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>

我不断收到类似 Unsupported Media Type 这样的回复。我不知道,还有什么办法。

【问题讨论】:

标签: angularjs


【解决方案1】:

假设您能够使用较新的“不稳定”版本之一,更改标题的正确语法是。

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

我发现 $resource 服务是用于构建应用程序的非常强大的工具,并且已经成熟到您不需要再退回到 $http 的程度了。再加上它的活动记录模式非常方便。

【讨论】:

  • 如何传递给“删除”对象以在请求正文中发送?
  • 嗨@brescia123,“通常”http 方法本身会指示您想要实现的所需操作,如上图DELETES 所示。如果您无法调用/公开 DELETE 方法,那么传入一个包含对象和所需操作的请求对象并非闻所未闻:{'action' : 'delete', {'target': myObj}}但我不喜欢这个,因为它不符合公认的 RESTful 服务原则。
【解决方案2】:

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

创建一个 Javascript 对象

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

var postObject = new Object();
postObject.userId = "testAgent2";
postObject.token = "testAgent2";
postObject.terminalInfo = "test2";
postObject.forceLogin = "false";

将对象发布到 API

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

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

由于 JSON 是发布到 API 的默认方法,因此无需重新设置。有关更多信息,请参阅 $http 快捷方式上的this link

关于您的代码,请尝试更改您的保存方法以包含这个简单的发布方法。

【讨论】:

  • 您好,先生,您的意思是我将使用 $resource 更改该行并将其更改为 $http?
  • 是的,整个返回部分可以用这个更简单的调用来替换。如何将其集成到您的项目中取决于您。
  • 我无法让它工作。我在控制台中不断收到以下错误: POST localhost:49653/api/warehouses 415 (Unsupported Media Type) 我认为它与 AngularJS 端的 application/json 和 ASP.NET WebAPI 的 application/x-www-form-urlencoded 有关结尾。它是这样工作的: data: "id=3&name=prueba&location=madrid", headers: {"Content-Type": "application/x-www-form-urlencoded"} 我希望能够在 WebAPI 上获取 json结束,虽然。还有什么帮助吗?
【解决方案3】:

设置 'Content-Type': 'application/json' 的正确方法是为保存操作设置一个 transformRequest 函数。

angular.module('NoteWrangler')
.factory('NoteNgResource', function NoteNgResourceFactory($resource) {

    // https://docs.angularjs.org/api/ngResource/service/$resource

    return $resource("./php/notes/:id", {}, {
        save : { // redefine save action defaults
            method : 'POST',
            url : "./php/notes", // I dont want the id in the url
            transformRequest: function(data, headers){
                console.log(headers);
                headers = angular.extend({}, headers, {'Content-Type': 'application/json'});
                console.log(headers);
                console.log(data);
                console.log(angular.toJson(data));
                return angular.toJson(data); // this will go in the body request
            }               
        }
    });
});

似乎没有清除查询参数的方法,请求将有两个...

【讨论】:

    猜你喜欢
    • 2012-07-11
    • 1970-01-01
    • 2019-10-26
    • 2020-11-14
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2013-04-15
    • 1970-01-01
    相关资源
    最近更新 更多