I can't seem to be able to get XMLHttpRequest() to work cross domain. I am able to get it to work cross domain via XDomainRequest() but I need to do a synchronous request.
var url = 'http://phpfilethatspitsoutjson.com';
// Can't get this to work
var req = new XMLHttpRequest();
req.open("GET", url, false);
req.send(null);
// This does work
xdr = new XDomainRequest(); // Creates a new XDR object.
xdr.open("GET", url); // Creates a cross-domain connection with our target server using GET method.
xdr.send(); //Send string data to server
xdr.onload = function () {
};
Also I do have header("Access-Control-Allow-Origin: *"); set in my url.
Related
xhr= new XMLHttpRequest(); //creates a new XMLHttpRequest
xhr.open("GET", "file.txt", false);
xhr.send(); // the request is sent
responsee = (xhr.responseText); // and the response is received
When the request is sent using 'xhr.send()' how can you get the source port for that particular request
I am creating a CORS call as follows:
createCORSRequest: function(method, url) {
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
console.log("Sending request with credneitials");
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
xhr.setRequestHeader('Authorization', 'Bearer bf6dcfd4e975a007dc8184be6bcf580c'); //Authorization details needed
return xhr;
}
The problem is that this is always sent as an OPTIONS call, which the server does not handle at all. If I remove
xhr.setRequestHeader('Authorization', 'Bearer bf6dcfd4e975a007dc8184be6bcf580c');
then it becomes a GET request but the server will not process it without the access token.
Is there a way to send the Authorization Header in the GET request ?
Or will I have to modify the server to handle OPTIONS requests ? I.e. preflights and so forth.
Thanks for the help.
If you set an Authorization header then you are making a complex request and you have to handle the OPTIONS preflight before the browser will make the GET request.
You can't set the header without handling the OPTIONS request.
On my webpage I have some javascript code to query Google Place API (GET) for response. Here's my code look like:
// Sending XHR request
var url = 'https://maps.googleapis.com/maps/api/place/textsearch/json?query=KPMG+Seattle&key=<<MY_KEY>>';
var xhr = createCORSRequest('GET', url);
xhr.setRequestHeader('Access-Control-Allow-Headers', '*');
xhr.setRequestHeader('Access-Control-Allow-Origin', '*');
xhr.send();
//**********************//
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
}
else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
}
else {
// CORS not supported.
xhr = null;
}
return xhr;
}
I am running this local HTML file in my browser, and got CORS error:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'null' is therefore not allowed access. The response had HTTP status code 405.
I am wondering what the problem can be (I added Access-Control-Allow-Origin to request header)? According to the Google Tutorial this should be enough to make a request?
Please help point out where I am doing wrong... Thanks!
Please see this post XMLHttpRequest Origin null is not allowed
Basically there is a security feature you need to disable to allow XHR of different origin if you are running from a local file.
See the first answer in the post.
Is there any way to get content type and content disposition of a url using java-script?
Thanks
Unfortunately, there isn't an API to give you the HTTP response headers for your initial page request.
Accessing the web page's HTTP Headers in JavaScript
Although you could make a new request and read those:
var req = new XMLHttpRequest();
req.open('GET', document.location, false);
req.send(null);
var headers = req.getAllResponseHeaders().toLowerCase();
alert(headers);
I want to get page from web-site using javascript.
I have url like:
http://not-my-site.com/random
From 'random' I will be redirected to another (random) page on the web-site.
Postman do everything like I want :) It's get whole page (html). But how can I do the same from javascript?
I tried CORS alredy following this guide http://www.html5rocks.com/en/tutorials/cors/ but without success. I still just get an error:
XMLHttpRequest cannot load http://not-my-site.com/random.
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
Code from tutorial:
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', 'http://not-my-site.com/random');
if (!xhr) {
throw new Error('CORS not supported');
}
xhr.onload = function() {
var responseText = xhr.responseText;
console.log(responseText);
// process the response.
};
xhr.onerror = function() {
console.log('There was an error!');
};
xhr.send();
And also I tried common xhr like this (got the same error):
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://not-my-site.com/random', true);
xhr.send();
This seems to be a problem of CORS not being configured correctly on the server. The below PHP code should allow any request from any domain. (If you're not using PHP, it should be easy to convert the below code into any other language, the clue is to write to the HTTP header).
Remember to place this code before any HTML is outputted.
$origin=isset($_SERVER['HTTP_ORIGIN'])?$_SERVER['HTTP_ORIGIN']:$_SERVER['HTTP_HOST'];
header('Access-Control-Allow-Origin: '.$origin);
header('Access-Control-Allow-Methods: POST, OPTIONS, GET, PUT');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: Authorization, X-Requested-With');
header('P3P: CP="NON DSP LAW CUR ADM DEV TAI PSA PSD HIS OUR DEL IND UNI PUR COM NAV INT DEM CNT STA POL HEA PRE LOC IVD SAM IVA OTC"');
header('Access-Control-Max-Age: 1');
Accepting requests from all domains is insecure. For a better (but slightly more complex) solution, see here: CORS That Works In IE, Firefox, Chrome And Safari