I'm getting "Cross-Origin Request Blocked" with the same domain - javascript

Well my JavaScript calls the url that is the part of the website, so I have no idea why this is "cross-origin".
My AJAX call:
$.ajax({
url: SITE_URL+'ajax_check.php?p='+P_ID,
//let's say SITE_URL is http://example.com/dev
success:function(result){
alert(result);
}
});
And this is the error I get in firebug:
"Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://example.com/dev/ajax_check.php?p=23. This can be fixed by moving the resource to the same domain or enabling CORS."

As mentioned by VoteyDisciple the url format must be exactly the same. In my situation the page url had a www prefix, but the ajax call url did not. So that's "cross-origin".

Related

Why does my API call work in chrome but not in my code?

I'm trying to call the Binance API to get the LTC price in BTC and I tested the link on my browser "https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC" How do i get the json file from that link into my javascript file?
$(document).ready(function() {
var url = 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC';
$.ajax( {
url: url,
dataType: 'jsonp',
type: 'GET',
success: function(data) {
console.log(data); //returns nothing
}
});
})
As mentioned in other answer, there is CORS issue. So you can try with proxyURL from client side as below,
$(document).ready(function() {
var url = 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC';
const proxyURL = "https://cors-anywhere.herokuapp.com/";
$.getJSON(proxyURL + url, function(playerData) {
console.log(playerData);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hope it helps.
The request to https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC provides json data this uses CORS policy
{"symbol":"LTCBTC","price":"0.01520100"}
JSONP would look like
myCallback({"symbol":"LTCBTC","price":"0.01520100"})
This looks like and works like a Javascript / PHP function.
The URL for a jsonp includes a callback in the URL ... https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC&callback=myCallback
But is not supported on this site
{"code":-1101,"msg":"Too many parameters; expected '1' and received
'2'."}
It might be openable with php on your site? I can not test from the system I'm on I don't have socket transport "ssl" setup on my tablet to test.
Yes it works from a PHP wrapper.
myJSONP(<?php echo file_get_contents('https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC');?>);
If you check on console after change dataType: 'jsonp' to dataType: 'json', you will get the following as your code and their script not on same host and they need to enable Access-Control-Allow-Origin to access from other domain. You may use cur if you use php.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
While performing the request from your browser or postman or fiddler you will get the result
But while performing a request from the application you will be failed with error message
Access to XMLHttpRequest at 'https://api.binance.com/api/v1/ticker/price?symbol=LTCBTC' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
The issue has to be fixed from your server side end.
Please refer
Cors understanding
Also, find the solution to the problem if you're using C# .Net as your backend
Solution for cors

Sending request to website using Javascript

i am trying to send an HTTP request to specific website and i am facing error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.google.com/. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
say for instance that i want to send request to Google.com and receive the HTML response.
my code was written using JQUERY AJAX:
function sendRequest(URL) {
$.ajax({
type:'GET',
url:URL,
success:function(result){console.log(result);}
});
}
Maybe it can help you : https://cloud.google.com/storage/docs/cross-origin#Troubleshooting%20CORS-Related-Problems
Look this one also : Access-Control-Allow-Origin error sending a jQuery Post to Google API's

Javascript CORS blocked but still shows data in packet capture

I have written a web app that is served to the browser from the local filesystem. I am attempting to make an HTTP GET request to another domain using jQuery's ajax method:
$.ajax({
type: 'GET',
url: "http://alerts.weather.gov/cap/us.php?x=0",
dataType: "text",
data: null,
success: function(data){
var x = data;
},
error: function(data, err) {
var x = err;
}
});
In the developer console, I am getting the error, "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://alerts.weather.gov/cap/us.php?x=0. (Reason: CORS header 'Access-Control-Allow-Origin' missing)."
Now: I understand what this means, and the purpose for this error.
Here's the really weird part: when I take a Wireshark capture of network traffic, I can see that the remote server is, in fact, serving up the content I requested.
Is that the way CORS works? Does it depend entirely on the client receiving data from the server and then refusing to work with it? I haven't found a clear explanation of where CORS is enforced; I expected it to be a server-side error and not a client-side error.
It's frustrating knowing that my browser is getting the data I requested but isn't letting me use it. Are there any workarounds?
CORS depends on the browser and the server. The browser should block the content; the server should respect the OPTIONS verb and return a proper CORS response.

Ajax call using jsonp not working, "Uncaught SyntaxError: Unexpected token"

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

Origin http://XXXXX.com is not allowed by Access-Control-Allow-Origin

I am trying to make a request to the yahoo wheather forcast like this
function parseXml(woeid)
{
$.ajax({
type: "GET",
url: "http://weather.yahooapis.com/forecastrss?w="+woeid,
dataType: "xml",
success: parse_wheather
});
}
and I get the following error message
XMLHttpRequest cannot load http://weather.yahooapis.com/forecastrss?w=1937103. Origin http://XXXXXXXX.com is not allowed by Access-Control-Allow-Origin.
I know that I can't make the request from localhost , but I am not running a localhost
How can I solve this problem ??
I know that I can't make the request from localhost
Actually, due to the same origin policy restriction you cannot send cross domain AJAX calls. So you are not only limited to localhost. You are limited to anything different than http://weather.yahooapis.com. So unless the page containing your javascript is hosted on this domain you cannot send AJAX requests to it.
Here's a guide you might take a look at about cross domain AJAX calls. In your case you could use a server side bridge. So you will define a server side script on your domain that will fetch the remote domain results and then you could send the AJAX request to your script in order to avoid violating the same origin policy restriction.

Categories