使用AngularJS处理HTTP POST请求

时间:2022-08-22 17:46:03

I'm developing a jsp which sends POST requests to a servlet. I would like to write content in raw payload instead of key-value form.

我正在开发一个jsp,它向servlet发送POST请求。我希望在原始有效负载中写入内容,而不是键值表单。

var addItemApp = angular.module('addItem',[]);
addItemApp.controller('addItemCtrl', function($scope, $http){
    $scope.addItemBnClicked = function(){
        var rqst = $http.post('http://127.0.0.1:8180/JSP/ws', "This is a test content");

        rqst.success(function(rspnData, status, headers, config){
            alert("Status: " + status);
        });

    }
});

Checking on the server side, I found that the payload doesn't contain anything. Please help, Thanks. ^^

在服务器端检查时,我发现有效负载不包含任何内容。请帮助,谢谢。^ ^

%%%%%%%%%%%%%%% Edit %%%%%%%%%%%%%%%

% % % % % % % % % % % % % % %编辑% % % % % % % % % % % % % % %

I use the following code to get the payload.

我使用以下代码获取有效负载。

String line = "";
String rqstRawBody = "";
while((line = servletRqst.getReader().readLine()) != null){
    rqstRawBody += line;
}

System.out.println("rqstRawBody: " + rqstRawBody);

The rqstRawBody is finally an empty string. I believe the above java code is okay, as I get raw payload correctly for those requests sent using the chrome-app Rest Client.

rqstRawBody最终是一个空字符串。我相信上面的java代码是可以的,因为我正确地获得了使用chrome-app Rest客户端发送的请求的原始有效负载。

1 个解决方案

#1


2  

You should change the Content-Type HTTP header. By default Angular sets that to application/json for a POST request.

您应该更改内容类型的HTTP头。默认情况下,角将其设置为application/json作为POST请求。

var config = { headers: { 'Content-Type': 'text/plain' } };
var data = { someKey: 'SomeValue'};
$http.post('/url', data, config).then(...);

Or you can set it as the default for all requests as shown in the documentation:

或者您可以将其设置为所有请求的默认值,如文档中所示:

module.run(function($http) {
  $http.defaults.headers.common['Content-Type']= 'text/plain'
});

#1


2  

You should change the Content-Type HTTP header. By default Angular sets that to application/json for a POST request.

您应该更改内容类型的HTTP头。默认情况下,角将其设置为application/json作为POST请求。

var config = { headers: { 'Content-Type': 'text/plain' } };
var data = { someKey: 'SomeValue'};
$http.post('/url', data, config).then(...);

Or you can set it as the default for all requests as shown in the documentation:

或者您可以将其设置为所有请求的默认值,如文档中所示:

module.run(function($http) {
  $http.defaults.headers.common['Content-Type']= 'text/plain'
});