I have a URL, which gives response on browser:
https://api.sandbox.paypal.com/retail/merchant/v1/locations
It gives:
{
"errorCode": 600031,
"message": "Missing access token",
"developerMessage": "You must provide an access token when calling this API. It can be passed as either a header of the form \"Authorization: Bearer \" or as a query parameter called access_token.",
"errorType": "oauth/missing_access_token",
"correlationId": "4de95cd8aa090"
}
I tried this:
$.ajax({
url: "https://api.sandbox.paypal.com/retail/merchant/v1/locations",
dataType: 'json',
type: 'POST',
success: function (data) {
console.log(data);
alert("success", data);
},
error: function (data) {
alert("fail", data);
console.log(data);
alert("Sorry..Please try again later");
},
});
But I am not getting the same response as I am getting on browser. I am getting error.
Please check here
http://jsfiddle.net/ajitksharma/wehGy/
However while debugging on Browser console I got the error:
XMLHttpRequest cannot load https://api.sandbox.paypal.com/retail/merchant/v1/locations. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
You can make AJAX calls to a backend API which is on another domain, however, it needs to return JSONP format and not just JSON, otherwise you get and error. This is due to same origin policy: https://developer.mozilla.org/en-US/docs/Web/Security/Same-origin_policy.
This discussion may be helpful to understand JSONP: Can anyone explain what JSONP is, in layman terms?
Since you don't have control over PayPal's API and you can't ask them to return JSONP to you, these requests to PayPal's API need to be done from the server-side script of your application.
Running this from any other location, for example JSFiddle, will give you the Access-Control-Allow-Origin error since you're making a cross-domain request. Please read further about the same-origin policy.
As for the first error, its because your request needs an API key from paypal. See this page about getting an API key and making a simple request.
As Lisa Stoz and kaminari suggested it is not possible to call a service in another domain without some patch work. Now as you see the response when you hit that url via browser it says you need to add an extra header to your ajax request something like 'authorisation'
Related
I'm using http://smmry.com/api for a small project. I'm fairly new to AJAX and have trouble using it. Here's what I have so far:
var a = $.ajax({
type:'POST',
url:'http://api.smmry.com/&SM_API_KEY=XXXXXXXX',
headers: {'Authorization': '["Expect:"]'},
data: {'SM_URL':'https://en.wikipedia.org/wiki/Human%E2%80%93computer_interaction'},
contentType:'application/json',
dataType: 'json',
});
console.log(a);
The error I'm getting:
XMLHttpRequest cannot load http://api.smmry.com/&SM_API_KEY=XXXXXXXX. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
I'm fairly sure it has something to do with headers. I have no idea what to do and would really appreciate it if someone could help me!
The error you are getting has to do with CORS. The XMLHttpRequest sends a preflight request, which is not supported by the SMMRY API, and is something that needs to be enabled server side. What can you do instead?
You can talk to their API through a server, e.g. a simple Node server.
You then send the XMLHttpRequest to your own server, where you do allow preflight request by allowing CORS (this is a simple line of code in a Node / Express server), and you forward the request to the SMMRY API and send the response back to your site. This process is called "proxying".
I have simple task - get users' data from instagram account. I use standard instagram api and angularjs.
Here is controllers' request method:
$http({
method: 'GET',
url: 'https://api.instagram.com/v1/users/6976008122/media/recent/?access_token=1030475459.50cd673.aa04db13898d4fsd9ff8fe5095b32f34&scope=public_content&count=4'
}).then(function(res) {
console.log(res);
}, function(err) {
console.log(err);
});
But I always get this error message:
Response to preflight request doesn't pass access control check: No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://project.loc' is therefore not allowed access.
The response had HTTP status code 405.
The first few pages of Google search has not helped, please help me understand and solve this problem.
Use jsonp, there's a good example located here: JSONP Instagram
Here's a link to another Stack Overflow question that explains how to do jsponp with angular Angular Jsonp
Problem
I'm working with a open data, city API for river levels, but when I make my ajax call using jsonp I receive an error for Uncaught SyntaxError: Unexpected token < which doesn't appear to be coming from my scripts.js
It is also my understanding that my ajax call might not be working because this API only spits out XML or json. I've tried to switch my dataType: json, but when I do that I receive the error below. Not particular sure if using jQuery's .getJSON is the best method to grab this data?
Data: http://opengov.brandon.ca/OpenDataService/opendata.html
Documentation: http://opengov.brandon.ca/api.aspx
Error (when switching dataType: json)
XMLHttpRequest cannot load http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
scripts.js
$(function(){
$.ajax({
url: 'http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel',
type: 'GET',
dataType: 'jsonp',
success: function(response){
console.log(response)
}
});
});
You may be interested in reading What are the differences between JSON and JSONP?
A "JSONP response" from a server is actually an executable script. The client runs the executable script, and the script happens to contain the data you want, supplied as an argument to a function. If the server doesn't serve an executable script, that server does not support JSONP.
For your next error, see "No 'Access-Control-Allow-Origin' header is present on the requested resource". Ajax requests to other domains are not permitted, unless explicitly allowed by CORS headers (like the Access-Control-Allow-Origin response header) from the server. Due to the same-origin policy, scripts on one origin are not allowed to access the contents of another origin. Cross-Origin Resource Sharing (CORS) is a way for the server to relax the same-origin policy.
I would suggest contacting the providers of the API and requesting CORS support. In this case, it really is as simple as serving an Access-Control-Allow-Origin: * header in the response. Per the W3C's own security recommendations for CORS:
A resource that is publicly accessible, with no access control checks, can always safely return an Access-Control-Allow-Origin header whose value is "*".
Alternatively, you can set up a reverse proxy server that fetches the API resources for you and serves them on your own origin, as noted in an answer on Ways to circumvent the same-origin policy. Since the same-origin policy is a browser restriction, you can have any server you control fetch the API resource and then serve the response to your browser.
The default data format is XML, but can be changed by setting the format query variable to "json" to return JSON formatted data.
You need to add &format=json to the end of the URL:
http://opengov.brandon.ca/opendataservice/Default.aspx?date=riverlevel&columns=date&dataset=riverlevel&format=json
I am trying to create wallet on Blockchain using Ajax but I am getting "Cross-Origin Request Blocked" error. My Ajax call is:
$.ajax({
type: 'POST',
url: 'https://blockchain.info/api/v2/create_wallet',
data: "cors=true&email="+email+"&password="+password+"&api_code="+code,
dataType:'json',
crossDomain: true,
beforeSend:function(){
},
success: function (data) {
}
});
When I post this I get error Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://blockchain.info/api/v2/create_wallet. This can be fixed by moving the resource to the same domain or enabling CORS.
On Blockchain they say that Some API calls are available with CORS headers if you add a cors=true parameter to the request
I have tried everything, I have tried to send this parameter as a GET as well as POST parameter, I have tried jsonp. I have also tried with the header Access-Control-Allow-Origin * but nothing seems to be working. Can anyone confirm if he managed to create blockchain wallet using Ajax call or they don't support CORS for this. Any help will be much appreciated.
Thanks
Hamza
I think it is safe to say that blockchain does not support CORS for their wallet API.
Your AJAX call above looks correct and you are getting a CORS blocked error.
And unlike some of their other APIs, the blockchain wallet API docs at https://blockchain.info/api/blockchain_wallet_api do not specify that calls are available via CORS with the cors=true query parameter.
There are some significant security implications when dealing with private keys and passwords in the browser using javascript. I suspect that is why they do not allow it.
The solution for this is insanely simple. Just do that request on the server side and then call your server script which does that request from your $.ajax() method.
I've been stuck on consuming a web service created in PHP, not sure what I'm doing wrong.. Ive created a fiddle example here : http://jsfiddle.net/e97AV/
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error.. in the browser when I visit the url it is returning valid json
My question is how would I know when to use jsonp or json? Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
heres the ajax code
baseUrl = "http://exclusivegetaways.co.za/api.php";
$.ajax({
type: "GET",
url: baseUrl,
data: {something : "something"},
//contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
alert("works");
alert(result);
},
error: function (a,b,cc) {
alert(a+b+cc);
}
});
I've since been able to pull json data from the ajax error object?? like so:
baseUrl = "http://exclusivegetaways.co.za/api.php?something=something";
$.ajax({
type: "GET",
url: baseUrl,
dataType: "json",
success: function (res) {
alert("worked");
//alert(res);
},
error: function(jqxhr) {
try {
f = JSON.parse(jqxhr.responseText);
...valid json returned here
} catch(err) {alert(err);}
}
});
This is because of a security restriction that prevents Ajax from querying remote locations.
As a workaround to enable access to a remote location via Ajax, you could build a custom URL in your webApp (in PHP for instance) which queries the distant API and returns JSON.
Then, in your JavaScript, you call this URL (from your application) via Ajax.
First: Always look at your JavaScript error console.
XMLHttpRequest cannot load http://exclusivegetaways.co.za/api.php?location=provinces.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'http://fiddle.jshell.net' is therefore not allowed access.
See also Ways to circumvent the same-origin policy
I've tried various combinations of things but keep on getting 404 not found feedback, when I specify jsonp i get no error message, but in the web console i can see a 404 error. in the browser when I visit the url it is returning valid json
This suggests that:
They don't support JSONP
They look at the HTTP headers and 404 your request to block access from Ajax (this isn't a good way to do that, the error code is misleading)
My question is how would I know when to use jsonp or json?
Usually by reading the documentation for the server you are trying to use
Also these service have been provided to me from an external source other than agreeing on json being returned how would I know if the problem is on my side or theirs?
Usually by working with whatever support is provided by the API provider (i.e. start with their documentation, then fall back to whatever means they provide for communicating with a human).
Due to Same Origin Policy your ajax request is allowed only if:
domain name, application layer protocol, and (in most browsers) port
number of the HTML document running the script are the same
In your case the application layer protocol is different, that's why your script fails.
Possible solutions are:
JSONP, which has to be provided by the server
CORS, which is a more 'elegant' and clean solution, but is not yet fully supported by IE (IE7 doesn't support it, IE8 has some limitations)
Answer taken from this link