FosRestBundle + AngularJS : Post request is empty - angularjs

I'm working on an API with FosRestBundle and AngularJS for the front part.
GET requests working but i have problems with POST requests. In the API controller the request object is empty..
Here is the front part
$http.post(Route.api + '/leads', {lead: "test"}).success(function(data) {
});
And here is the FosRestBundle controller
public function postAction(Request $request) {
var_dump($request->request->all()); // empty ? :(
}
Someone already have the same problem ?
Thanks ;)

Yes I had such problem, and I've solve this problem passing Content-Type header to Symfony, here is my code example
return $http({
method: 'POST',
url: Route.api + '/leads',
data: dataYouWantToSend, //see the note regarding this parameter
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
NOTE :
If you pass data parameter with object, you will receive in in the POST your data by JSON with key of your JSON's root.
If you want to receive it like form data, you have to convert it to querystring (e.g. ?deal=test&ok=1), for example if you're using jQuery too, you can convert it like this
var dataYouWantToSendQueryString = $.param(dataYouWantToSend);
hope it will help you too.
P.S. I've researched and haven't found how to convert object to query string in angular, so if Angular has such functionality, I will glad to know about it, if someone know, please comment.

Related

Error 400 when POST'ing JSON in angularjs + Spark Single Page Application

I'm new to Single Page Application area and I try to develop app using angularjs and Spark framework. I get error 400 bad request when I want to post JSON from my website. Here is code fragment from client side:
app.controller('PostTripCtrl', function($scope, $http) {
$scope.newTrip = {};
$scope.submitForm = function() {
$http({
method : 'POST',
url : 'http://localhost:4567/trips/add',
data : $scope.newTrip,
headers : {
'Content-Type' : 'application/x-www-form-urlencoded'
}
}).success(function(data) {
console.log("ok");
}).error(function(data) {
console.log("error");
console.log($scope.newTrip);
});
};
});
Values that are to be assigned to newTrip are read from appropriate inputs in html file. Here is server-side fragment:
post("/trips/add", (req, res) -> {
String tripOwner = req.queryParams("tripOwner");
String startDate = req.queryParams("startDate");
String startingPlace = req.queryParams("startingPlace");
String tripDestination = req.queryParams("tripDestination");
int tripPrice = Integer.parseInt(req.queryParams("tripPrice"));
int maxNumberOfSeats = Integer.parseInt(req.queryParams("maxNumberOfSeats"));
int seatsAlreadyOccupied = Integer.parseInt(req.queryParams("seatsAlreadyOccupied"));
tripService.createTrip(tripOwner, startDate, startingPlace, tripDestination, tripPrice, maxNumberOfSeats,
seatsAlreadyOccupied);
res.status(201);
return null;
} , json());
At the end I obtain error 400 bad request. It is strange for me that when I want to see output on the console
System.out.println(req.queryParams());
I get json array of objects with values written by me on the website. However, when I want to see such output
System.out.println(req.queryParams("tripOwner"));
I get null. Does anyone have idea what is wrong here?
I think the main problem is that you are sending data to your Spark webservice with the 'Content-Type' : 'application/x-www-form-urlencoded' header. Try sending it as 'Content-Type' : 'application/json' instead, then in your Java code declare a String to receive req.body(), you'll see all your data in there.
Note: When you try to acces your data like this req.queryParams("tripOwner"); you're not accessing post data, but you're seeking for a get parameter called tripOwner, one that could be sent like this http://localhost:8080/trips/add?tripOwner=MyValue.
I would advise using postman to post a request to your server and see if it works. Try a different content type too. Try using curl and play with the various headers you are sending. 400 suggests the wrong data is being sent or expected data is missing or the data is the wrong type but based on your code you've provided I can see nothing wrong (but see below).
When your server receives a request log all request headers being received and see what changing them does. If it works in postman then you can change your client code to mirror the headers postman is using.
Does your spark server validate the data being sent before your controller code is hit? If so ensure you are adhering to all validation rules
Also on looking at your code again your client is sending the data in the post data but your server is expecting the data in the query string and not in the post data?
What happens if your server just sends a 201 response and does nothing else? Does your client get a 201 back? If so it suggests the hook up is working but there is something wrong with the code before you return a 201, build it up slowly to fix this.
Ok, I managed to cope with that using another approach. I used Jackson and ObjectMapper according to Spark documentantion. Thanks for your answers.
You can see more about that here: https://sparktutorials.github.io/2015/04/03/spark-lombok-jackson-reduce-boilerplate.html
You're probably just needed to enable CORS(Cross-origin resource sharing) in your Spark Server, which would have allowed you to access the REST resources outside the original domain of the request.
Spark.options("/*", (request,response)->{
String accessControlRequestHeaders = request.headers("Access-Control-Request-Headers");
if (accessControlRequestHeaders != null) {
response.header("Access-Control-Allow-Headers", accessControlRequestHeaders);
}
String accessControlRequestMethod = request.headers("Access-Control-Request-Method");
if(accessControlRequestMethod != null){
response.header("Access-Control-Allow-Methods", accessControlRequestMethod);
}
return "OK";
});
Spark.before((request,response)->{
response.header("Access-Control-Allow-Origin", "*");
});
Read more about pre-flighted requests here.

How works simple table load with AngularJS?

I'm trying to learn AngularJS starting with that example: http://jsfiddle.net/mjaric/pJ5BR/
but when I tried to download in localhost, not works. I think that is a URL problem in /echo/json':
$scope.loadPeople = function() {
var httpRequest = $http({
method: 'POST',
url: '/echo/json/',
data: mockDataForThisTest
}).success(function(data, status) {
$scope.people = data;
});
};
But I don't know how to solve it. Any idea or hint?
My finally idea is load json from a search petition. It's possible that 'data' will be charged from web or online.
The url: '/echo/json/' is a feature of JsFiddle. If you look at the tabs to the left, in Ajax Requests you can see the usage. It probably won't work with this url in localhost.
You need to create a web project, where you can send your request. You could send some search parameters from client side, then filter the data with those parameters in the server and then return the filtered data to show.
The following article will give you some good ideas
http://tutorials.jenkov.com/angularjs/ajax.html
This link provides a hands on example by a really good tutor.
http://weblogs.asp.net/dwahlin/learning-angularjs-by-example-the-customer-manager-application

Angular wait for a $http call to execute the next function

I had been searching for this same issue here, I found something but all that seems to not be working for me. Let me describe my scenario:
I am adding some features to a Web app done by myself, that Web app is used to manage the developing of the webpage of some customers. Each customer has a webpage and for each customer there are a list of proposals webpages and who of the designers did that proposal, fine.
The list of the developers and be able to see who did what is the new thing in the Web app and the reason of my question, so, the problem is:
Once the web app loads I get the list of developers from the DB and a list of all the customers that have a webpage. So, the next thing the web app does is auto-select the first customer of the list and show its proposals in another list. To do that, the list of the developers is needed, but as it hasnt been still loaded I get the:
Cannot read property '0' of undefined
When I want to iterate over the $scope.developers object
What I do to get the developers is a $http call like this:
$http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
$scope.developers = data;
});
I know $http performs async calls, but i need something that waits until the $scope.developers has the data loaded.
The problem comes when I need to use the data supposedly stored in $scope.developers but obvously its not. I tried to call the function that uses the $scope.developers inside the .success function but the same happens.
I tried to use the solution in this thread but I get the same error.
How to wait till the response comes from the $http request, in angularjs?
Any help ?? If something in my question is not clear I will try to explain it better.
Please just define $scope.developers as empty array before $http call ie
app.controller("someCtrl", function($scope, $http) {
$scope.developers = [];
//....
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).success(function(data) {
$scope.developers = data;
});
//..
});

Can I use $http to get a javascript for my web page?

I am using the following code:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "/Scripts/Pages/Home.js", false);
xmlhttp.setRequestHeader("X-Custom-Header", "My Values");
xmlhttp.send();
var m = document.createElement('script');
m.appendChild(document.createTextNode(xmlhttp.responseText));
document.getElementsByTagName('head')[0].appendChild(m);
Can someone advise me if it is possible to get a javascript with $http and show me how I can do it inside a function that returns a promise when it is completed. The reason I would like to use $http is that along with the request for the js I need to send a custom header for authorization.
Please note that this question is different from the one suggested as a duplicate in that I am also wanting to find out if I can get a javascript and add it to the page DOM in the same way as it was done with the .setRequestHeader. Thanks
Since $http is a implementation for XMLHttpRequest in Angular, you can of course make requests to get the contents of a JS file.
You can set additional headers with $http like this:
$http({
method: 'get',
url: 'some/js/file.js',
headers: {
"X-Custom-header": "foo"
}
}).then(function (data) {
// do something with the DOM here
});
So as you can see, you are actually able to do that.

Recaptcha angularjs verify user's answer

I am using the following plugin https://github.com/VividCortex/angular-recaptcha in order to use recaptcha at a login form.
I am using the following code for verification
$http({
url: 'https://www.google.com/recaptcha/api/verify',
method: 'POST',
params: {privatekey: "key", remoteip: "userip", challenge: "challenge", response: "user_answer" },
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {
console.log(data);
if (valid) {
console.log('Success');
alert('Success');
} else {
console.log('Failed validation');
alert('Fail');
// In case of a failed validation you need to reload the captcha because each challenge can be checked just once
//vcRecaptchaService.reload();
}
});
But google server is not returning anything.
I updated the code but no luck.
I think you have a typo in your code:
post: 'GET'
Change that to method: 'GET' or method: 'POST'.
You can check out angular documentation on http to make sure you've written all the params right.
If this wasn't the source of your problems, you should post more details about your issue (what do you see in your networkl console for example).
Keep in mind that recaptcha validation must be done at server-side. I'm not 100% sure that you are doing that in the browser, but your code looks like it.
As Miguel Trias stated, you shall not validate directly from angularjs/javascript client, instead you should send the challenge and response field to your server and validate then.
Therefore you can use the uri you used (https://www.google.com/recaptcha/api/verify) or a plugin, e.g. if you use php see https://developers.google.com/recaptcha/docs/php. I'd prefer a plugin because it will save work.
Furthermore keep in mind that your private key should not be used in the client, this is why it is called private. It is only used to communicate between your server and the reCaptcha servers. The public key is used to communicate between your client and the reCaptcha servers.
For more info read the Overview

Resources