chunchiu Chan
chunchiu Chan

Reputation: 199

Working with HTTP POST request with AngularJS

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.

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.

Upvotes: 2

Views: 89

Answers (1)

Sunil D.
Sunil D.

Reputation: 18193

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

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

Upvotes: 2

Related Questions