Specifying date range params for $http GET request to Parse DB - angularjs

The following is a GET request I am making to Parse.com's RESTful API. I want to structure the request to only retrieve records that have been received today.
$http({
method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
// WHAT DO I PUT HERE?
createdAt: /* greater than 8am today, less than or equal to current time */
}
})
After reading from the Parse API docs about Query Constraints, I've modified the $http GET. However, it still returns all Orders.
var startDate = new Date();
var currentTime = new Date().getTime();
startDate.setHours(8);//set time to 8 am.
$http({ method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
where: {
"createdAt": { "$gte": startDate, "$lte": currentTime }
}
}
})
EDIT 1: Upon structuring my get request like so: I receive a 400 HTTP error, containing the following:
code: 107
error: "invalid date {1.433264918052e+12}"
EDIT 2 (SOLVED): I've solved the issue. After resolving the structure of the params property, I learned that the Parse API expects an ISO format DateTime. So, my final version looks like this:
var startDate = new Date().toISOString();
var currentTime = new Date().getTime().toISOString();
startDate.setHours(8);//set time to 8 am.
var deferred = $q.defer();
$http({ method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
where: {
"createdAt": { "$gte": startDate, "$lte": currentTime }
}
}
})
If someone would like to take this opportunity and give a thorough explanation, I would be happy to give them the answer (e.g. what benefit is there for Parse to use ISO over standard Unix epoch time?).

You can pass the from and to dates timestamp to pass a range of date. Try something like this.
var startDate = new Date();
startDate.setHours(8);//set time to 8 am.
$http({
method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
createdFrom: startDate.getTime(),
createdTo: new Date().getTime()
}
});
On the server side you can convert the timestamp to date object to pass it to DB stored proc or query.

Realized that I posted the answer in the question a long time ago. Updating this with an official answer for posterity.
I've solved the issue. After resolving the structure of the params property, I learned that the Parse API expects an ISO format DateTime. So, my final version looks like this:
var startDate = new Date().toISOString();
var currentTime = new Date().getTime().toISOString();
startDate.setHours(8);//set time to 8 am.
var deferred = $q.defer();
$http({ method: "GET",
url: "https://api.parse.com/1/classes/Order",
headers: {
"X-Parse-Application-Id": PARSE_CREDENTIALS.APP_ID,
"X-Parse-REST-API-Key": PARSE_CREDENTIALS.REST_API_KEY,
"Content-Type": "application/json"
},
params: {
where: {
"createdAt": { "$gte": startDate, "$lte": currentTime }
}
}
})

Related

Can't send params to Spring get method

I'm trying to make a get request with some params to a Spring get method. I'm using angular to make a call and this is my example
var apiUrl = 'api/trupci-filter';
var req = {
method: 'GET',
url: apiUrl,
headers: {
'Content-Type': "application/x-www-form-urlencoded" or "application/json"
},
data: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}
console.log(req)
return $http(req)
And this is my get method in Spring:
#GetMapping("/trupci-filter")
#Timed
public ResponseEntity<List<Trupci>> getTrupciWithFilter(
#RequestParam(value = "klasa", required = false) String klasa,
#RequestParam(value = "promjer", required = false) String promjer,
#RequestParam(value = "duzina", required = false) String duzina )
The call is successful but the params are always null. I can't find any solution to this simple thing and I'm losing my mind.
Can anybody help me?
HTTP GET request can't have data element, its for request body like for HTTP POST, PUT etc. Please use params for query string parameters.
var req = {
method: 'GET',
url: apiUrl,
params: {
klasa: "1",
promjer:"1",
duzina: "1"
}
}

Unable to send data to web api methods using angularjs

Hi I am developing one application using web api2 and angularjs. Finding hard time to send data to web api methods. I am having problem to send data as objects n PUT and POST methods. In delete and getbyid methods i am able to send single parameter but i am not able to send data as object. I am receiving null as below.
I am calling as below using angularjs.
this.saveSubscriber = function (sub) {
return $http({
method: 'post',
data: sub,
url: '/NCT_Users/',
// contentType: "application/json"
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
});
}
If i comment header and uncomment contentType in above code I am getting totally null object as below.
May i know why i am not able to bind object to model? Any help would be appreciated. Thank you.
var person = {firstName:"John", lastName:"Doe", age:46};
$http.post('url', person)
.success(function (response){
alert(response);
});
accesstoken is defined variable.you can define your variables to pass it to server
var person = {
firstName:"John",
lastName:"Doe",
age:46
};
$http.post('url', person)
.success(function (response) {
alert(response);
});
try this way.
var sub = {
User_CreatedDate: "",
UserEmailId: "",
User_Id: "",
User_MobileNum: "",
User_Name: "",
User_Password: "",
User_Role: "",
User_Status: "",
User_UpdateDate: ""
};
$http.post('/NCT_Users/', sub).success(function (response) { alert(response); });
the fields are filled by you
It happens like this because you are sending an JS Object via an 'application/x-www-form-urlencoded' header. You have to send the data as parameters, try this updated function:
this.saveSubscriber = function (sub) {
return $http({
method: 'POST',
data: $.param(sub),
url: '/NCT_Users/',
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
});
}

Issue with Posting JSON data with AngularJS

I am facing a specific issue with making a post call using Angular js, the below code fails with error:
Response for preflight has invalid HTTP status code 404
How ever if I make the same call by passing parameters in plain text format, by appending values directly in URL it works. Any help here is appreciated.
eg: https://sample.com/services/srest/restserver/v1.0/authenticate/login?username=rakesh&password=somepassword
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
data:postdata,
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login'
}).then(callback, errcallback);
}
return result;
});
Provide headers
angular.module("sampleApp2",[])
.service("apiCalls",function($http) {
var result;
var postdata = {username: "rakesh", Password: "somepassword"} ;
this.cobLogin = function(callback,errcallback) {
result = $http({
method:'POST',
url:'https://sample.com/services/srest/restserver/v1.0/authenticate/login',
data:postdata,
headers: { 'Content-Type':'application/json'}
}).then(callback, errcallback);
}
return result;
});
It sounds like you are using the wrong content type. The default is Content-type: application/x-www-form-urlencoded. You want Content-type: application/json. You can set this in the headers option. Check the $http docs
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': 'application/json'
},
data: { test: 'test' }
}
$http(req).then(function(){...}, function(){...});

How to post Json data with a key in angular js?

I have to send json object as a value with a key.
My Code:
var req = {
method: 'POST',
url: clientAdd_url,
headers: {
'Content-Type': 'application/json'
},
data: {Contact: $scope.clientinfo}
}
Contact is a key and $scope.clientinfo is a json object. But it's not working.
I checked in Postman, the format is like:
{
Contact: {
"BillingDetails": {
"CompanyName": "Shangrila Handicraft Shop",
"Address": "Kamaladi"
},
"ContactDetails": {
"ContactName": "Shyam Shrestha",
"ContactEmail": "shyam#gmail.com",
"ContactPhone": 9808909090
},
"ShippingDetails": {
"ShippingName": "Shangrila Handicraft Shop",
"ShippingAddress": "Kamaladi"
},
"Notes": "Test from Postman"
}
I would be grateful for your help.
place all those in to a obj as below...
$scope.datelvl = { "date": $scope.date, "tanklevel": $scope.Tank_level };
later call to backend controller for method like below:
$.ajax({
type: 'POST',
url: apiUrl + 'yourcontrollername/methodname',
data: datelvl,
contentType: 'application/x-www-form-urlencoded',
dataType: 'json',
success: function (data)
{
}
$scope.clientinfo looks like its a JSON object. By what I understand from your question, looks like you want to send $scope.clientinfo as a string. For that you could convert the JSON object to a string using the JSON.stringify
data: {"Contact": JSON.stringify($scope.clientinfo)}
see: http://www.json.org/js.html
Try this.It might useful.
angular.module('appCtrl1', []).controller('AppCtrl',function($scope,$http){
var tempData = {"Contact": $scope.clientinfo};
$http({
method: 'POST',
url: serverURL,
headers: { "Content-Type": "application/json" },
data: tempData,
}).success(function(data, status, headers) {
console.log(data);
}).error(function(data, status, headers) {
console.log(data);
});
}
Thank you everyone. I was told to send json data with a key as I have stated the original format though it has been little edited. So I was having a hard time. I have used the normal json post of angular in my projects. But since it was not the json, I could not send data through any process. I think many of you didn't get my question. But anyway I am so much thankful for your concern. This problem is solved. They made changes in their end.

Adding content-type header to Angular $http request

I'm trying to send HTTP request using the following code:
var editCompanyUrl = 'http://X.X.X.X:YYYY/editCompany';
var userId = localStorage.getItem("UserId");
var token = localStorage.getItem("Token");
var companyId = localStorage.getItem("companyId");
return $http({
method: 'POST',
url: editCompanyUrl,
params: {
token: token,
userId: userId,
companyId: companyId,
companyName: $scope.companyName,
},
timeout: 500
}).then(function (data) {
console.log(data);
//Store Company ID which is used for saving purposes
//localStorage.setItem("companyId", data.data.Company.id);
return data.data.Company;
}, function (data) {
console.log(data);
})
and handler of the request on the server side accepts requests with Content-Type: multipart/form-data. How can I add this content type to the request? I've tried many advices and tips from tutorials but no success. Could you please help me? In addition to it - what should I do when I will add a file with an image to this request? Can I just add it as additional parameter of the request?
Thank you very much!
Angular POST must be like below code.
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }
}
it should have data:{ }
so try to put your params: inside the data and it should work.

Resources