I am using the following URL to get data for a weather app.
http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP
I've used this API before, but this time I'm trying to load the data in using AJAX so the rest of my page doesnt reload when this data is fetched.
Here is my javascript
<script>
$(function () {
var zip = 16001;
$.ajax({
type: 'GET',
crossDomain:'true',
url: 'http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP' +zip,
success: function (data) {
console.log("Here is the data", data);
},
error: function () {
alert("Error loading data");
}
});
});
</script>
I keep recieving the following error in the console.
XMLHttpRequest cannot load http://wsf.cdyne.com/WeatherWS/Weather.asmx/GetCityWeatherByZIP16001. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:50733' is therefore not allowed access. The response had HTTP status code 500. weatherAjax.html:1
This makes it seem like their is an issue with accessing the data. But i've used this before with a simple form that the user input their zip code into. And it returned the data. The only difference now is I want to load the data using AJAX so the entire page doesn't reload. What am I doing wrong?
Previously you were sending the user's browser to someone else's website. They were leaving your site and all was fine.
Now you are trying to write JavaScript to instruct your visitor's browser to fetch data from someone else's website (which would use any auth/authz credentials they had) and give that data to your code.
Since the other website could be, for example, an online bank, this is forbidden unless the site you are requesting the data from gives explicit permission for you to access it.
For further reading, see the Same Origin Policy and HTTP access control (CORS).
Related
I have built a REST API with Node.js Express http://localhost:3000/api/feeds with node.js and filled with data.
router.get('/api/feeds', function (req, res, next) {
documentDBConfig.getAllDocuments()
.then(() => res.json(documentDBConfig.feedsArray));
});
Now i make a static website and want to use javascript or jquery to get data from my REST API. I used this code
$.getJSON( "http://localhost:3000/api/feeds", function( data ) {
console.log(data);
});
But it keeps saying
XMLHttpRequest cannot load http://localhost:3000/api/feeds. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63342' is therefore not allowed access.
I know i'm doing it wrong, but i couldn't find the correct way. How can i get this json content with my website from my REST API (http://localhost:3000/api/feeds) ?
Edit: I don't get this warning with explorer, but i can not get the content. And now i solved the chrome problem thus i don't get this warning anymore. But i can't read the content. That is not a duplication.
Now i get this warning
Failed to load resource: the server responded with a status of 404 (Not Found)
Can you show us your REST api code so we can help you ? You need to set some headers in your backend to allow requests coming from other origins.
If you happen to be using express, this will help you. But you could have built the REST api in another way, so please provide us with more information.
This is because you are accessing a resource from another domain.
You try to access http://localhost:3000 from http://localhost:63342.
You can read more about this here https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Access-Control-Allow-Origin
Basically you are performing a CORS request which means you are trying to call a resource on different server. So your REST api should allow CORS requests by adding the response headers allowing the UI server resource.
Please Refer to this question if it helps
I'm attempting to create an HTML-file that acts as a direct link to a cached site made by proxysite. Is there any way I can send a form containing a URL, without having the user fill in any field?
Sending it via ajax like so:
var params = {
"d" : "http://www.web.site/"
};
$.ajax({
url: "https://eu1.proxysite.com/includes/process.php?action=update",
type: "POST",
data: params
});
Seems to be purposefully blocked, as it returns this error message:
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
EDIT: I realize why the above won't work. Since I don't have access to the previously mentioned website, I am looking for a possible workaround.
The reason you are receiving the "No Access-Control-Allow-Origin" header is because the receiving server needs to provide CORS headers. If you have access to the proxysite you will need to set the following headers to allow your request to go through
<?php
header("Access-Control-Allow-Origin: *");
Where the asterisk is the domain you want to allow. If you leave the asterisk in the the server will accept all requests from any local scripts on any domain.
Regarding sending the form without having the user input any fields-- Yes, it's possible to send data without user input. The way you are doing it is the correct way to send data via the jQuery Ajax method.
I am trying to learn how to parse APIs using javascript and so I am trying to get some json through some get calls.
In my script I have
<script>
function foo() {
var request = window.superagent;
var url = 'http://www.google.ca';
request
.get(url, function(response) {
console.log(response);
})
.set('Accept', 'application/json');
}
foo();
</script>
No matter what url I use, I always get this error
XMLHttpRequest cannot load http://www.google.ca/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://server.com' is therefore not allowed access.
(index):22 Error: Origin is not allowed by Access-Control-Allow-Origin
at s.crossDomainError (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:7899)
at XMLHttpRequest.s.end.D.onreadystatechange (https://cdnjs.cloudflare.com/ajax/libs/superagent/1.2.0/superagent.min.js:1:8551)
I tried using various example get request urls like wikipedia, nba stats, google etc...that work fine when I enter the url into my browser but it does not work when I try to use javascript to download the data.
I am using a local apache2 server on my ubuntu laptop. I am also using the superagent library for javascript, but i also tried using jquery and ajax and it's the same error.
so apparently I need to use a url that uses cors. The thing is
http://savvastjortjoglou.com/nba-shot-sharts.html?utm_source=Python+Weekly+Newsletter&utm_campaign=5185ff0538-Python_Weekly_Issue_202_July_30_2015&utm_medium=email&utm_term=0_9e26887fc5-5185ff0538-312727397
this tutorial just did a requests.get(url) which was the nba stats url and got his data. He did not get an error? How can I use a url that doesn't use cors to get data?
CORS is implemented on the browser end as well, to not allow javascript load malicious content from unknown sites. You should also try using the CORS plugin if you are still trying to scrap on the client side.
https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en
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'
I am trying to use the Google Docs API to get spreadsheet data as XML, and eventually JSON data. I have put the URL (http://spreadsheets.google.com/feeds/list/0Aizy-VIdLC0QdDNNRkpfVncxQzZRNG9fMVhueXVMenc/1/private/values) in my browser, and I get the data, even when not logged in to Google.
When I try with jQuery Ajax, I get the "page not found" error.
$.get('http://spreadsheets.google.com/feeds/list/0Aizy-VIdLC0QdDNNRkpfVncxQzZRNG9fMVhueXVMenc/1/private/values', function(data) {
console.log(data)
});
I am guessing that same origin policy might be the cause of the Ajax error, so I tried with PHP, but I get the error.
echo file_get_contents("http://spreadsheets.google.com/feeds/list/0Aizy-VIdLC0QdDNNRkpfVncxQzZRNG9fMVhueXVMenc/1/private/values");
I am aiming to get the Google Docs spreadsheet data into a JSON object for use on a webpage.
How can I fix this error?
You have to be logged in in order to be able to retrieve the spreadsheet data.
Visiting http://spreadsheet.google.com/.../private/values while logged in results in a meaningful XML page. Trying to load the same page when not logged in, however, results in a "Page Not Found".
According to the response header from the JQuery response, the only cause of this error is not being logged in (shown below).
WWW-Authenticate: No credentials were included in your request.
See The Protocol Guide for the relevant documentation.
Supposing you double-checked your URL string, the reason could be same origin policy. You cannot fetch data from a different domain due to browser's strict security policy.
If you want to get past this, you need to use a different approach, such as JSONP.
You can read more about how to implement JSONP in jQuery on the Ajax documentation page.