My Javascript file generates a JSON and there are some necessary values which I want to send it to the link www.leaderpush.com/Send/Getjson?Endpoint=endpoint&P256dh=p256dh&Auth=auth
var obj = JSON.parse(t);
var endpoint = obj.endpoint;
var p256dh = obj.keys.p256dh;
var auth = obj.keys.auth;
But I cannot send it to another domain. When I try, the URL that is sent becomes www.AnyDomain.com/www.leaderpush.com/Send...
What is your suggestion?
You need to format the URL correctly.
url = "//www.leaderpush.com/Send/Getjson?Endpoint=endpoint&P256dh=p256dh&Auth=auth";
You need // at the beginning to indicate that the domain name of the URL follows, otherwise it's treated as a filename relative to the current URL.
BTW, this still might not work if the other domain prohibits CORS. You may need to make the request from your server rather than from the client.
Since you have not mentioned the protocol absolutely(HTTP / HTTPS) or relatively(//) in the request URL, the browser treats it as a path and appends the request URL after the origin domain. And the request domain does not seem to support and have valid HTTPS certificate and hence make sure your origin domain is HTTP and the request domain (//www.leaderpush.com) is CORS supported.
Note: Try including crossDomain: true in $.ajax() request header, in case the target server might serve on request to enable cross domain to the client.
Related
I am trying to access the JSON metadata corresponding to Python packages in the form http://pypi.python.org/pypi/<package_name>/json using JavaScript.
My code looks something like this:
var name = $('#name').val();
var url = 'http://pypi.python.org/pypi/' + name + '/json';
$.getJSON(url, function(result){
console.log(result);
});
The problem is that the url for the json is case sensitive, so for example, pypi.python.org/pypi/flask/json gets redirected to pypi.python.org/pypi/Flask/json since the package 'Flask' needs to have a capital F.
Thus, if name is flask, I get the error XMLHttpRequest cannot load https://pypi.python.org/pypi/flask/json. Redirect from 'https://pypi.python.org/pypi/flask/json' to 'https://pypi.python.org/pypi/Flask/json' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Any idea on how to properly access the json even if the package name has the wrong capitalization?
If you make the request through an open CORS proxy it should work; try changing your code to:
var url = 'https://cors-anywhere.herokuapp.com/http://pypi.python.org/pypi/'
+ name + '/json';
That sends the request through https://cors-anywhere.herokuapp.com, an open CORS proxy which adds the Access-Control-Allow-Origin response header to it and then passes that back to your requesting frontend code as the response.
That redirect response with the Access-Control-Allow-Origin response header is what the browser sees, so the browser will actually follow the redirect instead of stopping.
All the said, it seems like the pypi.python.org site should really be including the Access-Control-Allow-Origin response header in their 3xx redirect responses, so you might consider filing a bug at https://sourceforge.net/p/pypi/support-requests/ requesting that they do.
Getting "Access-Control-Allow-Origin" error while calling https url of the same site via javascript from page of the same site with http.
The site root url is set at the .cshtml file to use absolute path. When the page is cached and opened again, the site url shows as http while the root url remains https since it's cached and causes this "Access-Control-Allow-Origin" error.
I am able to fix the issue by setting "Access-Control-Allow-Origin" to "*" on the action method.
But this means it will allow for all domains, i want to allow it for my application or domain only.
How can i set it programmatically, so it will work across all environments?
Is there any other better way to set the site root url which will use absolute path?
what you are looking for is called CORS (cross-origin resource sharing, http://enable-cors.org/, https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS)
You do not have to use a wildcard on that header, you can set only a specific domain and even limit HTTP methods if you want to.
Access-Control-Allow-Origin: http://domain1.com
# if you want to, you can limit the methods too
Access-Control-Allow-Methods: GET, POST
As a general rule of thumb open your system only as much as you need to and try to keep the configuration as "tight" as possible.
You can cache a condition which test the protocol and then change the URL dynamically.
for example:
if (location.protocol == "https:") {
url = "https://....";
} else {
url = "http://....";
}
// your AJAX call goes here
More info about location protocol here.
I can make a GET request from PHP and get the correct response. This is the function I use:
PHP
function httpGet($url)
{
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch,CURLOPT_HEADER, false);
$output=curl_exec($ch);
curl_close($ch);
return $output;
}
A simple example:
$fakevalue='iamfake';
$url="http://fakeurl.com?fakeparameter=".$fakevalue;
$jsondata= httpGet($url);
$fake_array = json_decode($jsondata, true);
$weed_var=$fake_array['weeds']; // successfully obtained weed.
This function returns the response from the server.
Now I am trying the same HTTP GET request in AJAX, but I can't get the response.
Initially I thought the problem was with the JavaScript function that I use. Google provided with me lots of JavaScript functions for performing the HTTP GET request but they all had the same problem. The request returns an error instead of the data that I got when I used PHP.
JAVASCRIPT
var fakevalue = "iamfake";
var fake_data = {
fakeparameter: fakevalue
};
$.ajax({
url: "http://fakeurl.com",
data: fake_data,
type: "GET",
crossDomain: true,
dataType: "json",
success: function(a) {
$("#getcentre").html(a);
},
error: function() {
alert("Failed!");
}
});
Error from JavaScript
XMLHttpRequest cannot load http://fakeurl.com?fakeparameter=fakevalue. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.`
I know you are going to tell me to use CORS, but if it was because of the absence of 'Access-Control-Allow-Origin' header, then how did I get response for the same service in PHP?
With PHP (or anything else running on your server, or a standalone application (including those installed as a browser extension)), you are requesting data from Bob's server using your credentials (your cookies, your IP address, your everything else).
With Ajax, you are asking Alice's browser to request data from Bob's server using her credentials and then to make that data available to your JavaScript (which can then send it back to your server so you can see it yourself).
Bob might give different data to Alice then he would give to you. For example: Bob might be running Alice's eBanking system or company intranet.
Consequently, unless Bob's server tells Alice's browser that it is OK to make that data available to you (with CORS), the browser will prevent your JavaScript from accessing that data.
There are alternatives to CORS, but they involve either distributing the data using a file type that isn't designed to be a data format (JSONP) (which also requires Bob's server to cooperate) or having your server fetch the data from Bob and then make it available through a URL on your server (or some combination of the two like YQL does) (which means that you get the data Bob will give to you and not the data Bob will give to Alice).
Simple answer: PHP isn't affected by CORS. It is a restriction placed by the browser on client-side code, so that the accessed URL gets to allow or deny the request.
You are running into CORS, because you are doing an XMLHttpRequest request from your browser to a different domain than your page is on. The browser is blocking it as it usually allows a request in the same origin for security reasons. You need to do something different when you want to do a cross-domain request. Try this: http://www.html5rocks.com/en/tutorials/cors/
If you only want to launch a GET request, you might try using JSONP datatype="jsonp".
Examples: http://www.sitepoint.com/jsonp-examples/
I'm having troubles with collecting json values from a URL in my application. When I try to get them a error log is displayed in the console saying that origin is not allowed by access-control-allow-origin.
I researched a bit and found out that response headers have to be set to Access-Control-Allow-Origin: *
How can I do that using pure javascript? No jquery or any other library.
This is my current code:
<script type="text/javascript">
var xmlHttp = null;
xmlHttp = new XMLHttpRequest();
xmlHttp.open( "GET", "http://example.com/id=69", false );
xmlHttp.send( null );
console.log("JSON values from URL: ");
console.log(xmlHttp.responseText);
</script>
I researched a bit and found out that response headers have to be set to Access-Control-Allow-Origin: *
How can I do that using pure javascript? No jquery or any other library.
You can't, not unless your server is running JavaScript (NodeJS, etc.).
The server has to allow access to the resource from the origin of your document. The way it works is:
The browser asks permission to access the resource (this is called a "preflight" request), telling the server what resource it wants access to, etc.
The server replies with the appropriate headers telling the browser whether access will be allowed.
The browser sends the actual request.
The server responds to it (again including the relevant headers).
I believe there are situations where the pre-flight isn't necessary. All of that is handled for you by the XMLHttpRequest object.
Details in the Cross-Origin Resource Sharing specification.
You cannot do this on client side, your server must send these headers.
var url = "/example/somelink";
jQuery.get( url, params, callback); //works fine
var url = "http://www.yahoo.com";
jQuery.get( url, params, callback); //fails!
when I give the full URL of a site, get() fails...any idea why this is happening?
Thanks
You can't access a remote domain like this, only your own domain. The difference is the domain, not the full vs relative URL.
It's the same origin policy that's blocking you here, you have to use JSONP to get data directly or proxy the request through your own domain.
If by "fails", you mean that you're unable to access the HTML you hoped to receive, this is prevented by the browser for security reasons.
You can manipulate the response only if it comes from the same domain from which the request is sent.