当前位置: 首页 > 面试题库 >

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

华聪
2023-03-14
问题内容

嗨,大家好,我是AngularJS的新手,我需要您的帮助。

我需要做的就是将json发布到API并获得正确的响应。

这是我不知道在哪里编写此代码的JSON。

JSON格式

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

如果我做的正确,则不确定。

控制器

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

服务.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>

希望你能帮助我。

我不断收到诸如“不受支持的媒体类型”之类的回复…我不知道该怎么办…

任何建议或评论都将很棒。。谢谢!


问题答案:

在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快捷方式上的此链接。

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



 类似资料:
  • 我尝试用angular发送post请求,但是当我将content-type设置为application/json时,请求的content-type总是没有设置,HTTP方法总是被删除,所有发布的数据都从请求体中删除。这里是我的代码 这里是我的请求

  • 我正在使用OkHttp3创建一个多部分请求体。以下是工作curl请求。 删除,会从我们的Spring Boot服务器产生错误。 不支持内容类型“应用程序/八位字节流”。 所以很明显,我应该为指定Json类型。让我们使用OkHttp创建请求。 这产生了与上述相同的错误。因此我更改了代码如下。 现在,OkHttp请求生成器抛出了这个错误。 意外标头:Content-Type 使用空标头,创建请求正文,

  • 从"text/html"到"Application/json"的响应的标头类型。其他然后这个 am使用as头类型作为头(“内容类型”、“应用程序/json;字符集=UTF-8”) 但不是改变。

  • 我向Kafka传达的信息如下: 我有自己的MyMessage自定义解/序列化程序,关键字是一个简单的字符串

  • Content-Type实体头用于指示所述媒体类型的资源的。 作为响应,Content-Type标题告诉客户实际返回的内容的内容类型。浏览器在某些情况下会执行 MIME 嗅探,并不一定会遵循此标头的值; 为了防止这种行为,X-Content-Type-Options可以将标题设置为nosniff。 在请求(例如POST或PUT)中,客户端通知服务器实际发送了什么类型的数据。 Header type