Parameter in cloud function using Parse and Angular $resource - angularjs

I am trying to call this [cloud function]..
Parse.Cloud.define("getMyData", function(request, response) {
console.log('request is : '+JSON.stringify(request));
console.log('parameter is : '+request.params.name);
//...
response.success('Run method successfully');
});
using Parse REST api from an Angular front end.
$resource 'https://api.parse.com/1/functions/getMyData', {},
myCustomMethod:
method: 'POST'
headers:
'X-Parse-Application-Id': 'FjV0J.....'
'X-Parse-REST-API-Key': 'Tr7Sipvu....'
params:
name: 'William'
My cloud function gets called, but I can't seem to retrieve my name parameter :
I2015-05-16T00:51:08.497Z]request is : {"body":"{}","params":{},"installationId":"","user":null,"master":false}
I2015-05-16T00:51:08.497Z]parameter is : undefined
Why doesn't my parameter appear in params?
Is there a problem with using Angular $resource to make such API calls?

What put me on the right path was that it worked great when using a curl call - as documented here.
In the end, I was able to retrieve my parameter by using $http instead of $resource :
// In controler
$http.post 'https://api.parse.com/1/functions/getMyData'
,
name: 'William'
,
method: 'POST'
headers:
'X-Parse-Application-Id': 'FjV0J.....'
'X-Parse-REST-API-Key': 'Tr7Sipvu....'
.success (data) ->
$scope.data = data
It appears Parse expects parameters to be transmitted through data which isn't possible with Angular $resource.

Related

convert cURL to angularjs $http

I just started learning angularjs and i'm trying to get a token from an api. The curl command I have works fine when I use it in the terminal and can get the token just fine. I am having a hard time making it work using $http though.
Here's my cURL command:
curl --data "grant_type=authorization_code&client_id=CLIENT_ID&client_secret=SECRET_KEY&redirect_uri=http://localhost:9999&code=AUTH_CODE" https://www.twitchalerts.com/api/v1.0/token
Can anyone help me convert this using $http
Try this:
var data = {
grant_type :'authorization_code',
client_id :'CLIENT_ID',
client_secret :'SECRET_KEY',
redirect_uri :'http://localhost:9999&code=AUTH_CODE'
};
// Simple GET request example:
$http({
method: 'GET',//or POST
url: 'https://www.twitchalerts.com/api/v1.0/token',
data:data,
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
if not then try to this
....
data:data,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
....
For more information about angular $http https://docs.angularjs.org/api/ng/service/$http

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

AngularJS $resource Headers POST

I would like to know how to pass headers to AngularJS $resource method
Here is the factory method
.factory('DataRepository', function ($resource) {
return $resource(serviceUrlPrefix + '/api/v1/AppList/:id', { id: '#id' }, { 'query': { method: 'GET', isArray: false }, 'update': { method: 'PUT', AppList: '#req', headers: { 'X-Requested-With': 'XmlHttpRequest' } } });
});
Here is the call to the dataRepository
dataRepository.update({ id: req[uniqueIDColumn] }, req, function (data) {
},
function (error) {
});
This code works fine. But i have few queries
Question 1:
Rather than specifying the headers in the factory method , how can i specify it in the call to the factory method? I tried few methods but it didnt work out.
Question 2:
I specified the header in the update method in the factory. When i perform "Save" using that factory, that header has been taken by default. But i have specified it explicitly for PUT method. Right? Why and how?
Question 3:
If i would like to specify the header for the particular factory in common for all Http methods, what is the way to do it?
Question 4:
What is the nomenclature for passing the parameters and the significance of "#" symbol before parameter and also in the below part, AppList is the parameter name used in the WebAPI, is it mandatory that it should match the parameter name in the WebAPI method, if its not matching, its not working:(
AppList: '#req'
I'm afraid we don't use $resource, but it does depend on $http. We configure the header with the below. Not sure about the rest of your questions.
I will say that we also do not use $http directly. We created our own "requestHelper" service that we inject everywhere. That allows us to inject things before making calls to $http as well as catch the response before passing the result on to the real caller. Helps with common error handling.
Configure headers for $http:
module.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}]);

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.

$http.get with parameters not working

I am trying to send a GET request using AnguarJS $http.get function.
However, the shorthand version is NOT working. Why is that?
Working:
$http({
url: $rootScope.root + '/brands',
method: 'GET',
params: postData
}).success(function(data) {
console.log(data);
});
Not working:
$http.get($rootScope.root + '/brands', postData).success(function(data) {
console.log(data);
$scope.brands = data;
});
The 2nd parameter for the $http.get shortcut method is meant to pass in parameters such as cache control, etc. Only for $http.post does the 2nd parameter accept the post data. If you are using the shortcut for $http.get you will need to pass in the query parameters as part of the URL: $http.get($rootScope.root + '/brands?a=1&b=2')
Ref: http://docs.angularjs.org/api/ng.$http#methods_get

Resources