What headers are necessary to complete an XMLHttpRequest? - javascript

I am trying to access images from a Google Photos album and populate a webpage with those images. This goal has been completed before, but implemented with Axios (which I'm not very familiar with). My issue is that my origin (currently a local port) is not allowed by Access-Control-Allow-Origin. From the tutorials and examples I've followed, including this one from MDN, I thought my implementation allows the port I'm running on, but I still run into the same issue.
// This is not the actual album url; for privacy I have changed it
const ALBUM_URL = "https://my-google-photos-album-url";
$(document).ready(function()
{
GetAlbum();
});
function GetAlbum()
{
const xhr = new XHRHttpRequest();
xhr.open("GET", ALBUM_URL);
// Set the origin to the port we will be using
xhr.setRequestHeader("Access-Control-Allow-Origin", "http://localhost:8000");
xhr.onreadystatechange = function(data)
{
console.log(data);
}
xhr.send();
}
Expected Behavior: Print a string of HTML and JS as was shown in the linked example.
Actual Behavior: Gives an error indicating that "http://localhost:8000" is not allowed. Exact details are given below.
Error log:
Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.
XMLHttpRequest cannot load https://my-google-photos-album-url due to access control checks.
Failed to load resource: Origin http://localhost:8000 is not allowed by Access-Control-Allow-Origin.
What am I missing here? I have also tried setting "Access-Control-Allow-Origin" to "*", but without any luck. Any and all help is useful, thanks!

The CORS error that you get is returned by the server that you are trying to access - the server behind the https://my-google-photos-album-url.
If you have access to this server, you should set there the CORS policy that will allow the client (http://localhost:8000 in your case) to access its resources. Otherwise, I'm not sure you can access it.

Related

How to set the Access-Control-Allow-Origin to "*" using XMLHttpRequest object?

I am trying to send a request to my api deployed in Heroku. I used an XMLHttpRequest object to fire a request to the api. I am trying out a simple
GET and no tricks. However, I receive this error:
XMLHttpRequest cannot load https://xxx-xxxx-xx.herokuapp.com/api/foods/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
Which is normal for Chrome. However, I wanted to do this the way Postman handles it. How should I make the request to the api so that it allows everything?
I used this Chrome extension and it worked.
https://github.com/vitvad/Access-Control-Allow-Origin/
What I was able to figure out that it is basically setting this rule:
rule = {
"name": "Access-Control-Allow-Origin",
"value": "*"
};
However, when I try to set it using xhr.setRequestHeader() method, it doesn't work.
<script>
var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://xxx-xxxx-xx.herokuapp.com/api/foods/', true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onload = function(){
console.log(xhr)
}
xhr.send(null);
</script>
It is your API in Heroku that needs to set the header, not the web client calling it.
Your browser is following the same origin policy by not allowing your page to request a resource in another domain. Your server can use CORS to let the browser know it is ok to make a request from another domain to this particular resource, but this information needs to come from your server.
The extension and Postman are not following the same origin policy like the browser is doing. The browser needs to follow this policy for your security.
How you set those headers really depends on how you implemented your endpoint in Heroku.

getting status code from resource with No 'Access-Control-Allow-Origin' header present

I'm using good 'ol XMLHttpRequest to make a GET request to https://www.instagram.com/USERNAME. My goal is to confirm that a the instagram username entered by my user actually exists, and it would be great if I could confirm this on the client side.
For instance, try to make a GET request to https://www.instagram.com/9gag and you get a 200 back. https://www.instagram.com/sakjafkhdsafd and you get a 404 back.
Now, now... seems like Instagram does not allow CORS... because when I run XMLHttpRequest.send() I get the following error:
XMLHttpRequest cannot load https://www.instagram.com/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.
Ok, guess the server is going to have to take care of this... BUT! if I check my network tab, I actually see that the request is being made and I am getting a response back with the expected status code. I also get all the html, everything. What the...?
How is it that the browser (chrome in my case) is able to capture this but not my application?
Adding my code as requested:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.instagram.com/" + username, false);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
// do something...
}
}
xhr.send()
EDIT:
I just tested this on Firefox and I get a 301 back. I guess my question now is "what is chrome doing to get the expected status code on the network tab?"
Although the browser has successfully retrieved content, it is forbidding you to read any of it due to CORS.
CORS is a little confusing in itself - if the server was okay fulfilling the request, why does the browser block it? But okay, that's a security restriction that was pasted on in a backward-compatible way.
What is more surprising is that this is true even for errors: the server must add a special header to its response even to allow the client to read a status code or error message!
But the browser will display those in the browser console and network tab.

'Access-Control-Allow-Origin' error when getting data from the API with Axios (React)

I'm getting an a "XMLHttpRequest cannot load https://example.com. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8000' is therefore not allowed access."
This is my componenDidMount(), and I'm using axios to get the data from my API.
componentDidMount() {
this.serverRequest = axios.get(this.props.source).then(event =>{
this.setState({
title: event.data[0].name
});
});
}
I'm using "python -m SimpleHTTPServer" on the terminal, to run 'http://localhost:8000'.
I'm using the Chrome browser, and if I turn on the Chrome CORS plugin (to enable cross origin resource sharing), the app works, and I see data displayed from the API on the DOM. But I know that using the CORS plugin is bad, so how should I fix the 'Access-Control-Allow-Origin' error officially?
With Axios, can I somehow add dataType: "jsonp", if that would fix it?
This is a restriction made by the browser for security reasons when you try to access content in some domain from another domain. You overcome this, you need to set the following in your header
Access-Control-Request-Method
Access-Control-Request-Headers
Many sites restrict CORS. The best way to achieve your goal is to make your python server as a proxy. See the example.
//Request from the client/browser
http://localhost:8000/loadsite?q=https%3A%2F%2Fexample.com
//In your server
1. Handle the request
2. Get the query param(url of the website)
3. Fetch it using your python server
4. Return the fetching data to the client.
This should work.

How to make cross origin get request via angularjs http using food2fork api

I'm simply trying to make a get request using food2fork's search api in an angular app. Right now I've got no backend to the app, so everything is running client side, and I'm running the following (with the APIKEY replaced, of course):
$http.jsonp('http://food2fork.com/api/search?q=turkey&key=APIKEY&callback=jsonp_callback')
.then(function(response) {
console.log(response);
});
However, I'm Uncaught SyntaxError: Unexpected token : in the console. I assume this is because it's expecting a jsonp function rather than json.
If I run it as a jquery getJSON, as seen here:
$(document).ready(function() {
var url = "http://food2fork.com/api/search?q=turkey&key=APIKEY";
$.getJSON(url,function(data) {
})
});
I get No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:8080' is therefore not allowed access. - which may be because I'm running locally, but that hasn't been a problem in the past.
I just want to get the json that I get if I run the same request as a url in a browser. Any ideas?
No 'Access-Control-Allow-Origin' header is present on the requested resource
You are facing Cross Domain problem and what you should do is enabling CORS from your server side (the service running from localhost:8080)

Meteor.http.call() from my app.meteor.com

I have an application where I use Meteor.http.call() in a server side function.
var ret = Meteor.http.call("GET", "https://www.quandl.com/api/v1/datasets/SF1/<...>");
This works using a localhost meteor server: I have my data back in the ret variable.
I deployed the application to ruleoneinvesting.meteor.com and now I get this error using that same call:
XMLHttpRequest cannot load https://ddp--4645-ruleoneinvesting.meteor.com/sockjs/info?cb=p7czcbhqun. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://ruleoneinvesting.meteor.com' is therefore not allowed access. The response had HTTP status code 503.
This didn't helped.
Sorry, my fault. I was using a
fs.writeFile('../../../../../../data/')
in a folder that it was not allowed to write in *.meteor.com.
That caused the HTTP status code 503.
Since you're getting "HTTP status code 503", this may not be something you can or need to fix.
According to wicked peter, the problem may not be yours but the server's:
503 Service Unavailable
The server is currently unavailable (because it is overloaded or down for maintenance). Generally, this is a temporary state

Categories

Resources