angularjs code:
$http({
method: 'POST',
url:'/hello/rest/user/test',
data: {user: 'aaaaa'}
});
Server code:
#POST
#Path("/test")
public Response merge(#Context HttpServletRequest request) {
System.out.println(request.getParameter("user"));
if (request.getParameter("user") == null) {
return Response.status(Status.BAD_REQUEST).build();
}
return Response.ok().build();
}
request.getParameter("user") is a null. I cannot revice a parameter by this way.
If you want to use request parameter, you need to pass the data as
$http.post('/hello/rest/user/test', {
user : 'aaaaa'
}, {
headers : {
"Content-Type" : 'application/x-www-form-urlencoded;charset=utf-8'
},
transformRequest : [function(data) {
return angular.isObject(data)
? jQuery.param(data)
: data;
}]
});
Also read this question
You need to look at the body rather than for the post parameter...
You may not be receiving POST parameters.
You are receiving a body that looks like this {"user":"aaaaa"} and you need to parse that JSON response.
Related
I am trying to use angularjs POST (or even GET) to a servlet with the following:
var json = { hello: "world" }
var deffered = $q.defer();
$http({
method: "POST",
url: url,
headers: { "Content-Type" : "application/json" },
request: JSON.stringify(json)
}).then(data) {
if(data.data) {
deferred.resolve({
response : data
});
)
})
return deffered.promise;
within the servlet, simple:
String val = request.getParameter("request")
it never seems to see it
I have tried:
data: JSON.stringify({ request: json })
data: { request: json }
"request" : JSON.stringify(json)
etc
if I comment out the getParameter and just return a generic value using Gson
JsonObject json = new JsonObject();
json.addProperty("This", "works");
response.getWriter().print(new Gson().toJson(json));
that comes back fine so is there something within the angular POST I am doing wrong here? I have also tried using "GET" instead but same result.
EDIT: I would like to understand POST method and the "proper" way to get the data from the json object if getParameter is wrong please~
getParameter() returns http request parameters, you should add this params by using :
params: JSON.stringify(json)
Not with
request: JSON.stringify(json)
Take a look in params in get and params in post.
I've been digging at this but cannot figure this one out, here's the simple attempt I've made, I thought this was fine but it seems to still request as get....
this.request = function(url, requestData) {
return $resource(url, null, {
post : {
method : 'POST',
params : requestData || {}
}
});
};
Using it:
this.request('/some/api/url', {data : true}).post();
I can't seem to figure out how to get back a promise object so that I can use the repsonse data....
You want to create your resource like so:
$resource(url, null, {
post: {
method: 'POST'
}
});
And then:
this.request.post(
requestData,
function (successResponse) {
// Do whatever with response
},
function (failResponse) {
// Do whatever with response
}
);
This will send a POST request to url with requestData as the body.
Angular Code:
getAuthorizationStatus: function () {
var deferred = $q.defer();
$http({
method: "POST",
url: url,
data: {
username: $scope.username,
password: $scope.password
},
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
My Server side code:
[HttpPost]
public int ValidateUser([FromBody]Credentials credentials)
{
try
{
string username = credentials.username;
string password = credentials.password;
//Do stuff
}
catch (Exception ex)
{
throw ex;
return -1;
}
return -1; // not valid user
}
The problem I am having is I am able to hit the Api Method but the data inside is always null. I have tried several combinations like this:
data: JSON.stringify({
"username" : "username",
"password":"mypassword"
}),
No dice.
What am I doing in wrong ?
Enclose your data in $.param()
Example :
data: $.param({ username: $scope.username,password: $scope.password })
I would instead trying to change the default and appropriate behavior of $http's POST, instead let the server read the data from the right place. Taken from MVC controller : get JSON object from HTTP body?:
[HttpPost]
public ActionResult Index(int? id)
{
Stream req = Request.InputStream;
req.Seek(0, System.IO.SeekOrigin.Begin);
string json = new StreamReader(req).ReadToEnd();
InputClass input = null;
try
{
// assuming JSON.net/Newtonsoft library from http://json.codeplex.com/
input = JsonConvert.DeserializeObject<InputClass>(json)
}
catch (Exception ex)
{
// Try and handle malformed POST body
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
//do stuff
}
It turns out that MVC doesn't really bind the POST body to any
particular class. Nor can you just fetch the POST body as a param of
the ActionResult (suggested in another answer). Fair enough. You need
to fetch it from the request stream yourself and process it.
Using [FromBody] beside the action input param is enough to get the data from request. Your problem is that you override the content-type in your Angular code through headers:
contentType: 'application/json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' //*** Remove this!
}
It must be 'application/json' in order to send json data. Just remove that headers and it should work normally.
I am try to post data form $resource in angular js project. It is my code in factory
deletemenu: function(menudata ) {
return $resource(url+'/menu/delete', {}, {
delete_menu: {
method: 'POST',
params: {
entityType : menudata.entityType ,
sellerId : menudata.sellerId ,
menuId : menudata.menuId ,
parentMenuIds : menudata.parentMenuIds ,
menuItemId : menudata.menuItemId
},
isArray: false
}
}).deletemenu();
}
I declare method POST but the request is send as a query string not the post request. It send as a
URL+"menu/delete?entityType=I&menuId=25&menuItemId=20&parentMenuIds=4&sellerId=1"
How I send these data as a POST method.
I think this should work better for you
return $resource(url + '/menu/delete', null, {
delete_menu: {method: 'POST'}
}).delete_menu(menudata);
Here, I'm passing in the menudata as the first argument to the non-GET "class" action delete_menu which will use it as postData.
The objects returned by $resource are much more flexible than what you're using here. It looks like you should be able to make your service / factory much neater by returning the $resource instance instead of these individual functions. For example
.factory('menuFactory', function($resource) {
var url = 'whatever';
return $resource(url, null, {
delete: {
url: url + '/menu/delete',
method: 'POST'
} //, other actions here
});
})
Then you can call it with
menuFactory.delete(menuData)
Should we send json array or normal array as querystring in senchatouch2
in any case you can only send String in URL so if you have JSON then use Ext.JSON.encode to make it string and if you have JS Array use toString or join method to flatten the array before appending it to URL.
Since you said querystring so I suppose you and not doing POST request.
[EDIT]
Looking at your comment it seems you want to send some data to service for creation but in that case you should not send data as querystring, you should send it in message body. Following is example to send JSON data to your service:
var obj = new Object();
obj.loginEntry = new Object();
obj.loginEntry.userid = username;
obj.loginEntry.password = password;
var data = Ext.JSON.encode(obj);
Ext.Ajax.request({
url : 'http://myserver:port/service/entity',
method : "POST",
headers: {
/* Important because default is
* Content-Type:application/x-www-form-urlencoded; charset=UTF-8
* which is not supported by service
*/
'Content-Type': 'application/json'
},
params : data,
success : function(response) {
},
failure : function(response) {
}
}
);
[/EDIT]
While we use POST method to send parameters in Sencha Touch2 use jsonData in Ajax Request like,
Ext.Ajax.request({
url:'',
method:'POST',
disableCaching:false,
headers: {
'Accept':'application/json',
'Content-Type':'application/json'
},
jsonData: {
FirstName:fname //{"FirstName":["Sam","paul"]}
},
success: function(response)
{
console.log(response.responseText);
},
failure: function(response)
{
console.log(response.responseText);
},
});