I have a function which does a HTTP GET request on Parse, using the code below. (I'm using AngularJs).
$http({ method: 'GET',
url: 'https://api.parse.com/1/classes/foo',
headers:{
"X-Parse-Application-Id": "MYPARSEAPPID",
"X-Parse-REST-API-Key": "MYPARSERESTAPIKEY",
"X-Parse-Session-Token": UserService.sessionToken,
},
params: {
where:{"toto":{"$gt":42}}
}
}).success(function(data, status) {
/* DO SOMETHING*/
}).error(function(data, status) {
/* DO SOMETHING */
});
I wrote this code using Parse' REST documentation (https://www.parse.com/docs/rest#queries-constraints)
which give this example (curl):
curl -X GET \
-H "X-Parse-Application-Id:..............." \
-H "X-Parse-REST-API-Key:.............." \
-G \
--data-urlencode 'where={"score":{"$gte":1000,"$lte":3000}}' \
https://api.parse.com/1/classes/GameScore
This is the result of the AngularJS request above seen through Chrome's Dev Tools:
where:{"toto":{}}
And this this the result of the same code, without the '$' character (it doesn't work, but the requet is sent as it should):
where:{"toto":{"gt":42}}
As you can see, the constraint disappears because of the '$' character.
I supposed angular doesn't let us use '$' as it is used for Angular properties/methods.
Any suggestion/ideas/example will be very helpful.
Edited:
I tried to stringify the params as RobH said, click here to look at the result seen through Chrome's Dev Tools.
The result of this query seems ignore completly the given contraints, even if the '$' caracter hasn't been striped. I found that someone else tried to stringify the params (How to pass parameters to $http in angularjs?), but according to the last comment, it "does not work ({method:'GET', url:'/search', stringifiedJsonData} is not a valid JavaScript literal)". I'm not sure about the relevance of this comment as I'm new at AngularJs and web in general.
Any other ideas ?
Related
I'm trying to send data in a body using the GET method.
It's working fine when i try to run using POSTMAN/cURL/Python but it's not working using AXIOS(ReactJS).
cURL:
curl -X GET \
http://127.0.0.1:8000/xyz/xyz/ayx-api/ \
-H 'Authorization: Token 980e4e673a9cfb4c99cb35313f65a446aa44faf7' \
-H 'Content-Type: application/json' \
-H 'Postman-Token: 1ee27393-b4b0-446a-b613-bd319e02e3c8' \
-H 'cache-control: no-cache' \
-d '{"dataId": 1, "date": "2018-03-01", "days": 9 }'
this curl working fine
Using Axios:
import axios from 'axios';
const baseUrl = process.env.BACKEND_SERVER_URL;
export const fetchDataObjects = async() => {
const header = {
'Content-Type': 'application/json',
'Authorization': `Token ${localStorage.token}`,
}
const data ={"dataId": 1, "date": "2018-03-01", "days": 9 }
const res= await axios.get(`${baseUrl}/ayx-api/`,{data:JSON.stringify(data)}, {headers: header})
// above line need to helop
return res.data;
}
How can i send data in body using axios in get method?
Thanks in advance.
The HTTP GET method requests shouldn't have a request body, and axios can't create a GET request with a body. It also can't create a query string for you, if you want to pass a query string, you have to do it manually, or with something like qs:
axios.get(`${baseUrl}/ayx-api/${qs.stringify(data)}`)
UPD: turns out that even manually you can't add a body to a GET request using the fetch method in the console of your browser (I've tried to do it in Google Chrome 108 and Firefox 107 they both return similar errors Request with GET/HEAD method cannot have body.). I guess it'll take some time for browsers to support it. As a workaround you can try switching to POST method on both backend (with a different path to make no collisions) and frontend.
Original answer:
You can create a GET request with body. You need to pass the body to AxiosRequestConfig (the second parameter of the axios.get method).
let body = {hit: "floor"} //can be a string or an object (refer to the docs)
axios.get(`url`, {data: body})
AxiosRequestConfig also accepts headers if you need any.
axios.get(`url`, {headers: {"Key": "keykeykey"}, data: body})
Thought the documentation says that the data is
Only applicable for request methods 'PUT', 'POST', 'DELETE', and 'PATCH'
you can actually pass the body (tested in axios 0.27) and the server should¹ receive it. And you also need to make sure that the server will accept such request since the constrain in the specification was removed almost a decade ago.
¹ - Citation from MDN's GET page:
Note: Sending body/payload in a GET request may cause some existing implementations to reject the request — while not prohibited by the specification, the semantics are undefined. It is better to just avoid sending payloads in GET requests.
I'm using axios for NestJS e2e testing and NestJS 9.1 with ExpressJS will accept body in the GET request (yes, you can retrieve it with the #Body() decorator).
I'm trying to test AngularJS's post method out, but so far I have not figured out how to get it work.
Here is my code snippet.
parameter = { categoryName: '' }; <- just a dummy parameter purposely set to '' for testing purposes
this.httpService({
method: 'POST',
url: '/svc_templates/svc_fetch_category.php',<- Just echoing some JSON string.
data: parameter
}).then(function (response) {
console.log(response);
The response I'm getting is shown below.
It seems that a call to the php file is going through, but the actual data(JSON) is not returning for some reason...
Could anyone help me out?
Make sure that the server .php file is actually working using curl e.g.:
curl -X POST -d #filename.txt http://example.com/svc_templates/svc_fetch_category.php --header "Content-Type:application/json"
Where filename.txt contains the JSON data you want to send.
I have a working curl call:
curl -X GET \
-H "X-Parse-Application-Id: XXXX" \
-H "X-Parse-REST-API-Key: YYYY" \
-G \
--data 'where={"number":1}' \
https://api.parse.com/1/classes/Day
How do I translate this into an angular $http call? I have tried every permutation I can think of, and it still retrieves every Day object. Base on the documentation, I expected the following to work:
$http({method: 'GET', url: 'https://api.parse.com/1/classes/Day',
data: {"where": {"number": 1}}});
EDIT:
I updated my code to use the Parse JavaScript SDK as recommended in the accepted solution. I installed it using bower:
bower install --save parse
In my app.js I initialize Parse:
Parse.initialize(parseAppId, parseJavascriptKey);
The controller code is a lot more verbose than what I had before, but does work correctly and provides more flexible querying:
var Day = Parse.Object.extend("Day");
var query = new Parse.Query(Day);
query.equalTo("number", currentDay); // Only retrieve objects matching currentDay
query.include('challenge,quote'); // Related objects
query.find({
success: function(results) {
console.log("Retrieved object with id: " + results[0].get('id'));
$scope.day = results[0];
$scope.$apply();
},
error: function(error) {
console.log(err);
}
});
While Wayne is 100% correct, We have decided to go a bit further and wrote a parse-angular seed project for developing web apps. It can be found here.
After you pulled it, do a npm install
As usual, cloud code should go into cloud/main.js,
express code: cloud/app.js
angular code: cloud/public/js/
Note that: You will need to change your AppId and AppKey in
config/global.json
cloud/public/js/app.js
Then you should have a nice parse-angular project set up and good to go.
If there's anything wrong, please feel free to open a pull request. :)
Instead of using $http you should be using the parse javascript api instead. https://parse.com/docs/js/guide
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.
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