How to delete file/s through rest api in uploadcare - c#

I'm trying to delete file/s in uploadcare rest api using jquery ajax.
Here is my current codes for jquery:
$.ajax({
url: "http://api.uploadcare.com/files/" + $("#photoguid").val() + "/",
type: "DELETE",
contentType: "application/json"
});
My question is how to implement it properly because every time I call this, it redirects me to login page, that's what I see when checking in fiddler and I'm not sure where to put the authorization. I'm only using free trial for this.

The docs do say Rest calls must be done via https. https://uploadcare.com/documentation/rest/
As for the request headers looks like that was answered here:
How can I add a custom HTTP header to ajax request with js or jQuery?
Here is an example for your case:
$.ajax({
url: "https://api.uploadcare.com/files/" + $("#photoguid").val() + "/",
type: "DELETE",
headers: { "Authorization": "Uploadcare.Simple demopublickey:demoprivatekey" }
});
Since 2014-12-24, Uploadcare API allows cross origin requests so if you're up to exposing your private key or want to add roundtrip to your backend to get proper Authentication header value, go for it.

Related

Ember.js 2 Calls to .net API

I am building a SPA ember.js app that will hit a .net API via an ajax call.
ember.js
getData: function(){
$.ajax({
type: "POST",
url: "http://localhost:9001/controller",
dataType : "json",
headers: "Access-Control-Allow-Origin",
contentType: 'application/json; charset=utf-8',
success : function(data) {
return data;
},
error:function(data){
alert('test' + data);
}
})
}
It returns an error message : SyntaxError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': 'function () { return _emberRuntimeSystemString.fmt(this, arguments); }' is not a valid HTTP header field value.
I have been hammering away at this issue for a few hours now and I just can't seem to get around it. Also very new to ember.js.
If anyone has a better idea of whats going on...
Well,
the problem is in your headers. You are not giving "Access-Control-Allow-Origin" a value.
So you want something like
headers: {"Access-Control-Allow-Origin": 'value' }
Also, I don't think that particular header is used that way? I believe it's a header that the server sends.
Check this post out - How does Access-Control-Allow-Origin header work?
Pav

How to get url of the caller page that initiated the ajax call

My web service wants to know what is the page url of the caller.
I checked the HttpReq -> Url it is the actual web service Url. Also the HttpReq -> UrlReferrer but it is not right, neither.
Is it possible to find out the caller page url from server side at all? Or do I have to pass in the url via service dto?
Thanks for your help :)
If, for whatever reason, UrlReferrer doesn't work out for you then... the page where the request came from knows what its address is, right? Why not supply this data to the javascript that served the Ajax request, so you can send it up with the Ajax request?
Pass the page URL as a parameter to your web service by using the JavaScript document.location.href notation, like this:
$.ajax({
type: "POST",
url: "YourPage.aspx/DoSomething",
data: "{'pageUrl' : window.location.href}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
}
});
Then you can handle the pageUrl value in your service code.

Ajax - 'Origin localhost is not allowed by Access-Control-Allow-Origin'

I'm relatively new to Ajax and was just tasked with this cross-domain call. We have a text box on our web page that a user will use to preform a search of company names. By clicking a button next to the text box, the Ajax call will be requested. Unfortunately the web service is located in a separate domain, so this is naturally causing issues.
Below is my best attempt at making this work. I should also note, the purpose of this call is to return the results in an XML format, which will be parsed in the success portion of the request.
Here is the error message again:
Origin http://localhost:55152 is not allowed by Access-Control-Allow-Origin.
I'm at a loss as to what to do for a work-around, any ideas would be greatly appreciated.
function GetProgramDetails() {
var URL = "http://quahildy01/xRMDRMA02/xrmservices/2011/OrganizationData.svc/AccountSet?$select=AccountId,Name,neu_UniqueId&$filter=startswith(Name,\'" + $('.searchbox').val() + "\')";
var request = $.ajax({
type: 'POST',
url: URL,
contentType: "application/x-www-form-urlencoded",
crossDomain: true,
dataType: XMLHttpRequest,
success: function (data) {
console.log(data);
alert(data);
},
error: function (data) {
console.log(data);
alert("Unable to process your resquest at this time.");
}
});
}
This error is due to the restriction enforced in cross-domain resource sharing. This has been implemented as a part of security feature to restrict the clients(domain) of a resource via cross domain calls. When you send a request to the webservice or api or similar, it adds Origin header in the request for the server or destination (here your api) to validate if the request is coming from an authorized source or not. Ideally the api/server should look for the Origin in the Request header it received and probably validate against the set of origins(domains) which it is permitted to serve the resources to. If it is coming from a permitted domain it will add the same domain in the response header as "Access-Control-Allow-Origin" value. wildcard is also permitted for this, but the issue is that with wild card permission any one can make a request and get it served (with some restrictions like an api is authenticated via windows auth or cookies where you need to send the withCredentials value * is not allowed). it is not a good practice to use wildcard origin the response header which makes it open to everyone.
These are some ways to set the response header with the values:-
Access-Control-Allow-Origin: *
Access-Control-Allow-Origin: http://yourdomain.com
you can even add multiple Access-Control-Allow-Origin headers in the same response (I believe works in most browsers)
Access-Control-Allow-Origin: http://yourdomain1.com
Access-Control-Allow-Origin: http://yourdomain2.com
Access-Control-Allow-Origin: http://yourdomain3.com
On the server side (c# syntax) you would do this:-
var sourceDomain = Request.Headers["Origin"]; //This gives the origin domain for the request
Response.AppendHeader("Access-Control-Allow-Origin", sourceDomain ); //Set the response header with the origin value after validation (if any) .Depending on the type of application you are using syntax may vary.
Hope this helps!!!

Cross Domain AJAX POST 403 forbidden when attempting to execute a cs WebMethod

Pardon my noobiness in web development terminology.
I am trying to execute the following [WebMethod]:
public static void CreatePendingCaseFromChat(string userInputs)
{
//Do a bunch of stuff here with the userInputs string
}
With the following AJAX (which resides on another server):
$.ajax({ type: "POST",
url: "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat",
crossDomain: true,
data: JSON.stringify(parameters),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data){alert("success in ajax call")},
error: function (data){alert("error in ajax call")}
});
MyCode.aspx contains the following lines within the Page_Load() method:
Response.AppendHeader("Access-Control-Allow-Origin", "*"); //Allow Cross domain AJAX call, update the "*" to be a specific URL
Response.AppendHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
Response.AppendHeader("Access-Control-Allow-Headers", "content-type, x-requested-with");
If I do the following, instead of the ajax call:
var invocation = new XMLHttpRequest();
var url = "http://www.MyCoolWebDomain.com/Code/MyCode.aspx/CreatePendingCaseFromChat"
if (invocation) {
invocation.open('POST', url, false);
invocation.send();
}
else {
alert("no invocation");
}
Then I can confirm with FireBug that the following Response Headers are set:
Access-Control-Allow-Head... content-type, x-requested-with
Access-Control-Allow-Meth... GET, POST, OPTIONS
Access-Control-Allow-Orig... *
With the AJAX call, none of those headers are shown.
I would like to make this work either way, whether with the AJAX call, or with the XHR call.
For the XHR call I can't figure out how to send the userInputs string to the WebMethod.
For the AJAX call I can't get it passed preflight or w/e it's called (the OPTIONS call).
I've posted a bunch of code on question:
CORS - Ajax error function reports error code as 0 for an API request returning 401
It is using MVC4, but should give you everything you need to get this working.

Making a $.post call with jquery 1.7.1 to a WCF rest service

So I have the following working:
$.ajax({
type: 'POST',
url: 'user',
data: '{"FirstName":"John","LastName":"Doe"}',
contentType: "application/json",
dataType: 'json',
success: function (data) {
alert('success!' + data.Id);
}
});
however this fails (which should be equivalent):
$.post('user', '{"FirstName":"John","LastName":"Doe"}');
Any idea what's wrong? Is $.post somehow incompatible with WCF rest?
No, the two are not equivalent at all. Look with FireBug, Fiddler, ... and compare the 2 requests. In the second example you are not setting the contentType: "application/json" request header. You are not setting it because the $.post method doesn't allow you to.
And the server doesn't accept your request because since you are trying to POST to a JSON enabled service, it expects the request to be JSON and of course the client to set the application/json content type request header. You are posting some string and since you don't indicate what this string represents through the content type header, the server doesn't know what to do with it and drops the request.
This is to say that you should use $.ajax as in the first example to invoke your service. Actually I'd recommend you a slight modification and instead of:
data: '{"FirstName":"John","LastName":"Doe"}',
use:
data: JSON.stringify({"FirstName":"John","LastName":"Doe"}),
This will ensure that if tomorrow you decide to deal with someone else than Mr. Jon Doe, like for example Mr. Jon O"Hara, your JSON will still be properly encoded which is what the JSON.stringify method does. It is natively built into modern browsers but if you need to support some legacy browsers you could include the json2.js script to enable it.

Categories