Unable to work Cloud Code httpRequest HEAD method - parse-platform

Not sure if I'm doing this wrong but I want to make a cloud code httpRequest to validate URLs. I wanted to use the HEAD method and save on some data traffic but specifying HEAD seems to do exactly the same as a GET... seems like I'm getting the full body as well.
Parse.Cloud.define('validateURL', function(request, response) {
var params = request.params;
var url = params.url;
Parse.Cloud.httpRequest({
url: url,
followRedirects: true,
method: 'HEAD'
}).then(function(httpResponse) {
// Redundant
var httpObject = {
buffer: httpResponse.buffer,
cookies: httpResponse.cookies,
data: httpResponse.data,
headers: httpResponse.headers,
status: httpResponse.status,
text: httpResponse.text
};
response.success(httpObject);
}, function(error) {
response.error(error.message);
});
});
I guess the question is, is this my problem or Parse.com's problem (or both or neither?)

Your httpRequest looks correct. You might want to file a bug report.

Related

Do I need to use fetch() to get a Parse.com query?

I'm using ReactJS and changing a simple local database setup to a Parse.com class adapting a link saver from this repo: https://github.com/peterjmag/reading-list
I want to switch the fetch call for the native to parse .save()
Can I use the fetch or should I rewrite the function to use the parse.com language?
Adding the link is declared on this
LinkActions.addLink.listen(function (link) {
fetch('//localhost:3001/links/', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
url: link.url
})
})
.then(function(response) {
if (response.status >= 400) {
throw new Error('Bad response from server');
LinkActions.addLink.failed(link);
}
return response.json();
}).then(function (newLinkData) {
LinkActions.addLink.completed(link, newLinkData);
});
});
EDIT
The new code looks something like this:
OK. So my new code looks something like this now.
LinkActions.addLink.listen(function(link) {
var LinkListing = Parse.Object.extend("LinkListing");
var linkListing = new LinkListing();
linkListing.save({
url: link.url
}, {
success: function(linkListing) {
// The object was saved successfully.
},
error: function(linkListing, error) {
// The save failed.
// error is a Parse.Error with an error code and message.
}
});
});
Am I missing something?
You can either keep the fetch and use the parse.com REST API, or refactor your code to use the Javascript API, icnluding functions such as save. I recommend refactoring to the Javascript API because it would make your code much shorter and clearer.
For example, two things which definitely shouldn't be your concern are adding headers to every request and comparing every response status to 400.

How-to correctly make a Parse.com Parse.Cloud.httpRequest from the client-side?

I'd like to make a http request from my cloudcode that gets called on my clientside.
I found this a bit confusing at first so hopefully this helps.
In your Cloud Code main.js
Parse.Cloud.define("POSTfromCloud", function(request, response) {
//runs when Parse.Cloud.run("POSTfromCloud") on the client side is called
Parse.Cloud.httpRequest({
method: "POST",
headers: {
"X-Parse-Application-Id": "[PARSE_APP_ID]",
"X-Parse-REST-API-Key": "[PARSE_REST_ID]",
"Content-Type": "application/json"
},
//adds a new class to my parse data
url: "https://api.parse.com/1/classes/newPOSTfromCloudClass/",
body: {
"newPOSTfromCloudClass": {"key1":"value1","key2":"value2"}
},
success: function (httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse);
},
error:function (httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(httpResponse.status);
}
}); //end of Parse.Cloud.httpRequest()
});
On your client side. This can be placed anywhere in any language, just use the Parse.Cloud.run to call the matching Parse.Cloud.define you placed in the cloud. You use the
Parse.Cloud.run('POSTfromCloud', {}, {
success: function(result) {
console.log("Posted a new Parse Class from Cloud Code Successfully! :"+ JSON.stringify(result))
},
error: function(error) {
console.log("Oops! Couldn't POST from Cloud Code successfully.. :"+ error)
}
});
}
Your Result: Assuming your POSTing
(here if you want to delete this new object your url would append the object id like so /newPOSTfromCloudClass/60j1uyaBt )
Know it doesnt have to be a httpRequst cloud function. You can do "anything" in the define and run functions.
NOTE: Also seen my other related question on passing params in this here

How-to correctly pass params between Parse Cloud Code and the Client? (httpRequest Example)

I've seen some examples, read the docs and read other question however I'm still not quite sure where to add/properly add params to be passed between Cloud Code and my Client side correctly.
For Instance, Here I am creating a new class from a httpRequest in my Cloud Code
In my Cloud Code main.js
Parse.Cloud.define("POSTfromCloud", function(request, response) {
//runs when Parse.Cloud.run("POSTfromCloud") on the client side is called
Parse.Cloud.httpRequest({
method: "POST",
headers: {
"X-Parse-Application-Id": "[PARSE_APP_ID]",
"X-Parse-REST-API-Key": "[PARSE_REST_ID]",
"Content-Type": "application/json"
},
//adds a new class to my parse data
url: "https://api.parse.com/1/classes/newPOSTfromCloudClass/",
body: {
"newPOSTfromCloudClass": {"key1":"value1","key2":"value2"}
},
success: function (httpResponse) {
console.log(httpResponse.text);
response.success(httpResponse);
},
error:function (httpResponse) {
console.error('Request failed with response code ' + httpResponse.status);
response.error(httpResponse.status);
}
}); //end of Parse.Cloud.httpRequest()
});
on my client side
Parse.Cloud.run('POSTfromCloud', {}, {
success: function(result) {
console.log("Posted a new Parse Class from Cloud Code Successfully! :"+ JSON.stringify(result))
},
error: function(error) {
console.log("Oops! Couldn't POST from Cloud Code successfully.. :"+ error)
}
});
}
My Result:
Bam! Got that working correctly. Now lets say I want to make my url one of many parameters passed how do I do this?
As I was asking this I was also tinkering with some things because I coundn't get anything to pass correctly (or it would return as an empty value) so here I have and example on how I can pass parameters into this.
in my cloudcode main.js
Parse.Cloud.define("POSTfromCloud", function(request, response) {
//HERE- make a new instance of 'myValue' for Cloudcode to handle
var myValue = request.params.myValue;
Parse.Cloud.httpRequest({
method: "POST",
....[blah blah]
//AND HERE- placed that here in my body, **note:** you shouldnt store tokens like this, ignore what I named it
body: {
"newPOSTfromCloudClass": {"yourToken":myValue,"key2":"value2"}
},
client side
var myvalue = "I'm The VALUE";
Parse.Cloud.run('POSTfromCloud', {myValue: myvalue}, {
success: function(result) {
Result: this should have passed the param correctly. Again ignore me using the title "yourToken", you shouldn't be storing tokens like that.
This took a while to put together, I hope this can help someone.

AJAX JSON with ServiceStack

I have spend over 10 hours trying to figure this out and looking at similar examples from other people but unfortunately I haven't been able to find out what's my problem here.
I have a ServiceStack Webservice setup:
http://example.com/v1/getuser?code=abcd&lastname=doe&format=json
If I run the above via the browser I will get the following:
[{"nameresult":"joe"}]
I am trying to get this via making an ajax call as follow:
var code = $("#code_field").val();
var lastname = $("#lastname_field").val();
$.ajax({
url: "http://example.com/v1/getuser",
type: "POST",
data: JSON.stringify({
code: code,
lastname: lastname,
format: 'json'
}),
contentType: "application/json; charset=utf-8",
success: function (data) {
var returned_data = data;
alert('returned_data=' + returned_data);
},
error: function (xhRequest, ErrorText, thrownError) {
console.log('xhRequest: ' + xhRequest + "\n");
console.log('ErrorText: ' + ErrorText + "\n");
console.log('thrownError: ' + thrownError + "\n");
}
});
When I run the above, I get the following:
returned_data=[object Object]
Does anyone knows how could I get the json result, nameresult=joe? I am assuming that [object Object] contains [{"nameresult":"joe"}] but I am not entirely sure because I cannot see inside the object :(. thanks so much.
LATEST UPDATE - PROBLEM SOLVED!
I figured out the problem I was having. It had to do with ServiceStack and not with the Ajax call. My problems was the following, I hope it helps someone else one day that may face the same issue.
1.- I needed to enable CORS support on ServiceStack in order to allow posting parameters from Ajax:
File: AppHost.cs
//Permit modern browsers (e.g. Firefox) to allow sending of any REST HTTP Method
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders = {
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
{ "Access-Control-Allow-Headers", "Content-Type" },
},
});
Plugins.Add(new CorsFeature());
this.RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpReq.HttpMethod == "OPTIONS")
httpRes.EndServiceStackRequest(); //httpExtensions method
// =>after v.3.9.60, => httpRes.EndRequestWithNoContent();
});
2.- My getuser method was in the GET instead of POST. I moved that to the POST and problem solved.
Moved getuser from here: public object Get(...) into here public object Post(...)
Thanks to all for helping me figure this out.
Use console.log to output returned_data by itself:
console.log(returned_data);
This will display the JSON object:
{"nameresult":"joe"}
Your original alert concatenates the string "returned_data=" with the JSON object, and thus the object is converted to a placeholder string "[object Object]" by the browser.
I often put my label in one log, and the object in another:
console.log('returned_data:');
console.log(returned_data);

Can't get $.ajax or $.get to work

I have this $.ajax (using jquery) code, it originally was the $.get that is now commented but for some reason I'm always getting the error and I can't find anything wrong with it =/, am I overlooking something?
$.fn.randomContent = function(options){
var contentArray = new Array();
var dType = "html";
var defaults = {
xmlPath: "../xml/client-quotes.xml",
nodeName: "quote"
};
var options = $.extend(defaults, options);
alert(options);
$.ajax({
type: "GET",
url: "../xml/client-quotes.xml",
dataType: "html",
success: function(){
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
},
error: function(){
alert("Something Went wrong");
}
});
/*$.get(defaults.xmlPath, function(){
alert("get");
$(defaults.nodeName).each(function(i){
contentArray.push($(this).text());
});
$(this).each(function(){
$(this).append(getRandom());
});
}, type);//$.get*/
};
Here's the getRandom() function:
function getRandom() {
var num = contentArray.length
var randNum = Math.floor(Math.random()*num)
var content = "";
for(x in contentArray){
if(x==randNum){
content = contentArray[x];
}
};
alert(content);
return content;
}
It could be that the browser is caching your GET requests. In this case, either:
ensure the server is controlling your cache options (using cache-control settings of private or no-cache)
change the method of your AJAX call to POST instead of GET
differentiate your GET request by adding querystring parameters that change with each request
I prefer option #1, specifically because POST operations are intended to change something on the server, and so we should use that method when our actions do in fact modify server state. GET requests on the other hand, are requests that do nothing more than read data.
I feel a GET request is more appropriate for this task, and so in my own code I would prevent the caching of the response.
Does that url have to be absolute? I've never tried doing ajax requests with a "../" in it. Do you have FireBug installed? You could examine the response header from the sever.

Resources