angular POST not working with servlet - angularjs

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.

Related

Retrieve data from angular post request

right now my situation is that I have a post request from an Angular module trying to send some data to an URL handled with node.js and Express.
tickets.js:
$http(
{
method: "post",
url: "/ticketDetail",
headers: {"application/json"},
data: {detail : "test"}
}).then(function successCallback(response)
{
$scope.detail = response.data;
}, function errorCallback(response){});
app.js:
app.post("/ticketDetail", function(req, res)
{
console.log(req.data.detail);
res.json(req.data);
}
It looks like req.data is undefined.
How am I supposed to retrieve the data from my request in my URL handler?
You need to get the data from the body of the req
var qs = require('qs');
app.post('/', function(req,res){
var body = qs.parse(req.body);
var detail = body.detail;
console.log('details',detail); //prints test
});
I believe your post doesn't match the AngularJs syntax. Your $http.post should be like ;
$http.post('/ticketDetail', data, config).then(successCallback, errorCallback);
So for some reason, in your URL handler you are not supposed to access the field data: {detail : "test"} with req.data but with req.body.
app.post("/ticketDetail", function(req, res)
{
console.log(req.body.detail); // prints "test"
res.json(req.data);
}

What is type of data angular sending?

What is type of data angular sending? I use laravel + angular. I`m trying, but this script return 405 error. Method not allowed.
.controller('adminCtrl', function( $scope, $http ){
$scope.collection = [];
$scope.newData = [];
$scope.newrecord = function() {
$scope.collection.push($scope.newData);
$http({
url: '/newrecord',
method: "POST",
data: $.param($scope.collection),
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(function(data){
console.log(data);
})
}
})
You are getting 405 - Method not Allowed because the server you are sending your request does not have POST it the white list of methods allowed to be used to perform requests to that given API.
It's not an angularJS issue, it's a server configuration issue.
$http sends data as json.
You do not need to serialize params using "$.param", data is plain javascript object, which is send to your REST endpoint.
So attach just "$scope.collection) and do not set Content Type manually, it is json by default.
POST can be send also with convenience method.
$http.post('/someUrl', data, config).then(successCallback, errorCallback);

Slim, Postman and AngularJs : $app->request->getBody() vs $app->request->post()

I'm a beginner. I've written a test application made of an AngularJs GUI on the client side and a PHP API on the server side.
This is the angular service handling the requests
myApp.factory('Book', ['$resource', 'API_URL', function($resource, API_URL){
return $resource(API_URL + '/books/:bookId', {bookId: '#bookId'}, {
get: { method: 'GET', isArray:true },
update: { method: 'PUT'},
save: { method: 'POST'},
delete: {method:'DELETE'},
});
}]);
When I submit a book from the Angular app I can catch the POST in Slim by using
$post_a = json_decode($app->request->getBody());
//$post_b = $app->request->post(); //this would be empty
When I use Postman and I perform a POST I can catch the POST in Slim by using
//$post_a = json_decode($app->request->getBody()); // this would be empty
$post_b = $app->request->post();
I don't get why there is this difference. Could you please explain?
Am I not meant to catch the post just with $app->request->post(); in both the cases? Why the post coming from Angular can be caught only with $app->request->getBody()?
The $app->request->post() method retrieves key/value data submitted in a application/x-www-form-urlencoded request. If the request uses a different content-type (e.g. application/json), you can retrieve the raw request body with the $app->request->getBody() method and decode it as necessary. Let me know if you have further questions.
You could still use
$post_b = $app->request->post()
in Slim.
As long as you call this REST service from html form (AngularJS) by passing the data as form value formatted instead of as JSON.
If in AngularJS you have the data in JSON format, you have to translate it first into form. Below is the example how to invoke this REST service:
Object.toparams = function ObjecttoParams(obj) {
var p = [];
for (var key in obj) {
p.push(key + '=' + encodeURIComponent(obj[key]));
}
return p.join('&');
};
$http({
method: 'POST',
url: url,
data: Object.toparams(myobject),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
myobject is the data in JSON format that is going to be created
Thanks Josh..Your answers works for me.
Steps to follow:
1.You need to send request in json format under raw tab like this:
{"username":"admin","password":"admin"}
2.You need to set Content-Type to application/json in the headers.
That's it and it will work.

pyramid not work with angular $http post

$http({method: 'POST', url: 'http://localhost:5001/products', data: {token: $scope.product.token}}).success(
function () {
alert('success');
}
);
In the pyramid side, request.POST show that NOVars: Not a form request. Not an HTML form submission( Content-Type: application/json)
I am using cornice to provide my api(/products) and I thinks it is pyramid's problem.
Does anyone have a solution?
Angular sends the post body (data) as application/json while forms are normally sent as application/x-www-form-urlencoded. Pyramid parses the body and let you access it in request.POST when it's encoded as a normal form.
It is not be possible to represent every data encoded the Angular way (json) as a key/value pair like is provided by pyramid API.
[
1,
2,
3,
4
]
Solution on Pyramid side
It can be solved per view or globally
Per view
This is the pyramid way and the most flexible way to handle this.
#view_config(renderer='json')
def myview(request):
data = request.json_body
# deal with data.
return {
"success" : True
}
Globally
Pyramid can most likely be set to assume a body encoded as application/json is an object and its properties be put in request.POST.
Solution on Angular side
As with the pyramid side, it can be solved per request and globally.
Per request
You need to send the data the way forms are normally sent:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
},
data: xsrf
}).success(function () {});
Globally
To send posts as form by default, configure the $httpProvider to do so.
angular.module('httpPostAsForm', [])
.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$httpProvider.defaults.transformRequest.unshift(function (obj) {
var str = [];
for(var p in obj) {
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
}
return str.join("&");
});
}]);
Then include this module in your app:
angular.module("app", ["httpPostAsForm"]);
AngularJS $http.post is different from jquery's. The data you pass is not posted as a form but as json in the request body. So your pyramid view can not decode it as usual. You have to either:
directly access the request body and decode it in your pyramid view;
or modify your angularjs code to post your data as form content : see this other question in stackoverflow
the answer is angular $post do OPTIONS request first and then do the POST request, get data form the request.json_body
Use req.json_body if you post some json-decoded content. req.GET, req.POST, req.params only cope with from submissions. Btw, $http -> ngResource -> restangular ...
Try setting contenttype in $http, something like below.
$http(
{
url: url,
contentType: "application/json",
data: data,
method: method
})
.success(function (response) {
successcb(response);
}).error(function (data, status, headers, config) { errorcb(data); });
};
You can simply get the POST data this way:
query = json.loads(request.body)

Sending json array as querystring in senchatouch2

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

Resources