how to enable Access-Control-Allow-Headers in xmlhttprequest - javascript

An XMLHttpRequest cannot load error arises when using HTML with Jquery to call an API:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://api.xxxx.com/col?system=xxx&keyid=xxxxx&rtype=city&region=" + citiCd);
xhr.onreadystatechange = function () {
if (this.readyState == 4) {
var datax = JSON.stringify(this.responseText);
//my stuff
}
};
xhr.send(null);
When run, it produces this error:
XMLHttpRequest cannot load
http://api.xxxx.com/col?system=xxx&keyid=xxxxx&rtype=city&region=DLI.
Origin localhost is not allowed by Access-Control-Allow-Origin.
How do I enable access? I tried xdomainrequest without luck.

I've faced that issue a few times and it should be resolved on the server side.
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Related

Fetch XML without getting blocked (CORB)

For example I want to fetch https://www.w3schools.com/xml/simple.xml
to my website http://example.com.
This is the code
var xhr = new XMLHttpRequest();
xhr.open("GET", 'https://www.w3schools.com/xml/simple.xml', true);
xhr.onload = function () {
if (xhr.readyState === 4 && this.status === 200) {
console.log(this);
}
}
xhr.send();
I'm getting an empty response and a warning saying
Cross-Origin Read Blocking (CORB) blocked cross-origin response https://www.w3schools.com/xml/simple.xml with MIME type text/xml. See https://www.chromestatus.com/feature/5629709824032768 for more details.
Then I had been studying these CORB rules. Some developers are saying that it is not possible to get data from another origin.
But is it really the case?
In the project I'm working on, it is a public xml feed, and since the owner are updating the feed quite often - and I would like to have my website in sync with the feed - I assume it is not possible? Do I really have to create a xml file, and copy-paste the xml data and upload it to my server each time?
Or is there a way to fetch this data directly from the url somehow?
You could create a PHP script like this:
<?php
header("Content-type: text/xml");
echo file_get_contents('https://www.w3schools.com/xml/simple.xml');
?>
Call this simple.php and then amend your Javascript to call simple.php instead:
var xhr = new XMLHttpRequest();
xhr.open("GET", 'simple.php', true);
xhr.onload = function () {
if (xhr.readyState === 4 && this.status === 200) {
console.log(this);
}
}
xhr.send();

How to set CORS header in an AJAX call with pure JavaScript that is hitting other rest service?

I am having following JS function that gets called on html page load. When the page loads I see following error in the Firefox console logs.
Firefox Console Log:
"NetworkError: 403 Forbidden - http://localhost:8080/publicKey/lookup/TRUUS2"
TRUUS2
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8080/publicKey/lookup/TRUUS2. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).
publickey.js
function loadPublicKey() {
var xmlhttp = createCORSRequest('GET', 'http://localhost:8080/publicKey/lookup/TRUUS2');
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
alert(this.responseText);
document.getElementById("keyDiv").innerHTML = this.responseText;
}
};
}
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;
}
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
return xhr;
}
I have already added xhr.setRequestHeader("Access-Control-Allow-Origin", "*") statement to fix the CORS issue but no luck. I am looking for pure JS implementation.
Note: I am able to hit the http://localhost:8080/publicKey/lookup/TRUUS2 URL successfully through Postman and getting the response as well. No issues there.
Not sure what am I missing. Please guide.
Based on the input provided by Rory, I removed the xhr.setRequestHeader("Access-Control-Allow-Origin", "*") from the JS and added snippet #CrossOrigin(origins = "http://localhost:8084") in my controller and that solved the problem.
#CrossOrigin(origins = "http://localhost:8084")
#RestController
public class PublicKeyLookupController {
//code removed for brevity
}

Cross-Origin Request Blocked: in javascript using XMLHttpRequest

I am trying to send a HTTP request in javascript using XMLHttpRequest and so I am using the following code in an HTML file. I have a server running which returns a dictionary of form {'test' : 'string'}.
<script type="text/javascript">
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:5000/test", true);
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.send();
xhr.onreadystatechange = processRequest;
console.log(xhr.status)
function processRequest(e)
{
if (xhr.readyState == 4)
{
alert(xhr.responseText);
}
}
</script>
However in spite of adding the header, I am getting a Cross-Origin Request Blocked: error in my console when I try to print xhr.status in the console it shows 0 as response.
I am using flask server which shows a bad message error on using HTTPS, so I am using an HTTP request.
You can not control CORS from front end. You have to put the CORS module to your back end server.
check the link flask cors.

Ajax Yelp API Call from Javascript

I'm trying to make a call to the Yelp API from JavaScript, but getting an error. Below is my code. I believe I will have to use Oauth, but I don't know where should I put it in the header.
function doAjax(){
var xhr = new XMLHttpRequest();
var url = "http://api.yelp.com/v2/searchterm=cream+puffs&location=chicago";
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
var some = JSON.parse(xhr.responseText);
}
}
xhr.open('GET', url, true);
xhr.send();
}
The problem is that you are trying to access a resource that is on a different domain from your application. In this case your application resides on http://fiddle.jshell.net and the resource is at http://api.yelp.com.
CORS is one way to get around this, see here:
http://en.wikipedia.org/wiki/Cross-origin_resource_sharing

Ajax - "Access-Control-Allow-Origin" Error

I'm trying to work with the Livestream API to see if a certain channel is live but keep getting this error:
XMLHttpRequest cannot load http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft. Origin http://www.webdevstl.com is not allowed by Access-Control-Allow-Origin.
Do I need to run it through PHP or am I doing something wrong in my ajax call? It's pretty straight forward code:
function getActive(){
if(window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
}
else
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var json = JSON.parse(xmlhttp.responseText);
console.log(json);
}
}
xmlhttp.open("GET", "http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send();
}
getActive();
You're running into restrictions imposed by the Same Origin Policy. In short, AJAX calls to a different domain are prohibited and will fail - unless explicitly permitted by the remote host.
You need to either use JSONP (mostly applicable to data returned by APIs) or proxy the request through your own server/domain.
CORS would also be an option, but that assumes you having access to the remote server's config.

Categories

Resources