Dude with fetch use [duplicate] - javascript

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 4 years ago.
(translated by Google)
Hello
I have a doubt regarding the use of fetch
From my server, I access images that are hosted on another server (such as a CDN)
This piece of code works correctly. The image is shown.
var img = document.getElementById( obj );
img.src = data-src;
// data-src has the url of the image https://serverCDN/image/bar/foo.jpg
However, within the same script, same servers, same image involved, the following code does not work.
Returns the error "Access to fetch at 'https://serverCDN/image/bar/foo.jpg' from origin 'http://myServer' has been blocked by CORS policy: No 'Access -Control-Allow-Origin 'header is present on the requested resource. If an opaque response serves your needs, set the request's mode to' no-cors' to fetch the resource with CORS disabled."
fetch ( data-src ), {})
.then (
function (res) {
console.log (res)
}
);
Because the first piece of code works and the second does not?
I'm confused.
I would be interested in using fetch, because I need to access the RESPONSE HEADERS sent by the CDN server
EDIT (FOR DUPLICATED TAG)
I undestand the CORS concept, but
The Dude is...Why, the first piece of code works and the second does not?

The problem is, that the server on https://servercdn/image/bar/foo.jpg does not send a Cross Origin header. By default, JavaScript XMLHttpRequests (XHR) are bound to the same domain. You can change this behaviour by adding cross origin HTTP header to the target server.
Or a simpler way: Use jsonp: https://www.w3schools.com/js/js_json_jsonp.asp

Related

Using AWS Lambda REST URL from Local Host [duplicate]

This question already has answers here:
Configure CORS response headers on AWS Lambda?
(5 answers)
Closed 3 years ago.
I have only been using AWS Lambdas for a few weeks, and I am trying to learn more about them specifically how to implement a Lambda I write on a webpage.
I have a project, I am working on in my local machine which is just a website, and some JavaScript with Axios. When I deploy my code to AWS Lambda using Serverless at the end of the output , I get a url, lets call it THE_URL. When I copy and paste this page into my browser, I am brought to a web-page which has the response on it as I expect.
But on my website, I have this script being called when I press a button,
axios
.get("THE_URL")
.then(data => console.log(data))
.catch(err => console.log(err));
And this gives me the error Access to XMLHttpRequest at 'THE_URL' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Which I have looked up and it seems is fairly common. I have researched and looked into the possible solutions that there were online, and that lead me to passing in as headers, and flagging the request so it looked like this,
axios
.get("THE_URL",
{headers: {
"Access-Control-Allow-Origin": "*"
},
withCredentials: true
}
)
But with this, I then get an error which looks like this Access to XMLHttpRequest at 'THE_URL' from origin 'null' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Which I have not been able to find any solutions for online. So I figured I would ask here, and see if any of you people have ran into any errors like this?
Thanks for reading!
The CORS header should be in your server, not the client. The server controls which client domains may access it. By adding the "*" you are allowing any site to request a resource from your server, including localhost (assuming your lambda is publicly accessible)
Update the lambda to return the Access-Control-Allow-Origin: * header.
https://serverless.com/framework/docs/providers/aws/events/apigateway/#enabling-cors

CORS Issues Executing Get Requests Using Axios/Github [duplicate]

This question already has answers here:
from origin 'xxx' has been blocked by CORS policy: [duplicate]
(2 answers)
Closed 3 years ago.
I'm trying to authenticate over OAUTH API using Axios. The initial request is just a simple GET to get the auth token.
axios.get(
"https://github.com/login/oauth/authorize?client_id=$ID"
).then((res) => { console.log(res) })
I immediately get:
...from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I can use an href link and it works totally fine. What could be the issue here?
In simple terms, when you are using the anchor tag, it is a link to the original site. When user click on a tag, user will be redirected to that site. But when an AJAX request user will stay in your site and sends an ajax request to the server(github in this case).
When using HTTP protocol there is a header call origin which will tell the backend server where user is from, see the below picture
So if server does not allow sources other than it self, this security check will be failed and the AJAX request won't be success. Please let me know if you need more clarifications and I'll be glad to help. Hope that helps.

No 'Access-Control-Allow-Origin [duplicate]

This question already has answers here:
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 4 years ago.
Hi I'm new to javascript and API calls and I'm trying to make an API call using the following javascript code:
var url = 'https://labs.bible.org/api/?
passage=random&type=json&callback=myCallBackFcn';
var ourRequest = new XMLHttpRequest();
ourRequest.open('GET', url);
ourRequest.onload = function(){
console.log(ourRequest.responseText);
};
ourRequest.send();
When I refresh my page I get the following error:
Failed to load
https://labs.bible.org/api/?passage=random&type=json&callback=myCallBackFcn:
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'null' is therefore not allowed access.
Can anyone help me with this? Also, can you explain exactly how to fix it?
You have a cross-origin issue, let's explain it.
Browser downloaded js file from example.com website, now js file wants to make ajax to xyz.org website, this is a cross-origin request and so the browser asks xyz.org "do you allow example.com to access your resources"? the browser knows the answer from 'Access-Control-Allow-Origin' Response header.
But xyz.org didn't send this header so the browser assumed xyz.org doesn't want anyone but him to access his resources so the browser just refuses your request.
Note that cross-origin request happens too when you access js file in a URL beginning with file:// and origin here is set to null because js isn't downloaded from any server yet origin null is different from xyz.org.
Solution: if you control xyz.org just make it add Access-Control-Allow-Origin to response headers, you can look the internet for value format for this header.
If it's a third party website you have to call its admins and if they refuse to add the header then you simply have no solution in pure js but hey only browsers respects this policy, if you make a desktop application then it doesn't care and an example of this is Postman the REST APIs tester.

Cannot Access API. No 'Access-Control-Allow-Origin' header is present on the requested resource [duplicate]

This question already has answers here:
Why doesn't adding CORS headers to an OPTIONS route allow browsers to access my API?
(36 answers)
How does the 'Access-Control-Allow-Origin' header work?
(19 answers)
No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API
(26 answers)
Closed 4 years ago.
I'm trying to access an API with a fetch request,
On some website it works like a charm, but on some others I get this error,
If I load the link from my browser it works...
Failed to load https://bittrex.com/api/v1.1/public/getticker?market=btc-usd:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Origin 'https://mydomaine.com' is therefore not allowed access. If an opaque
response serves your needs, set the request's mode to 'no-cors' to fetch the
resource with CORS disabled.
I'm lost, and I tried everything.
I get the exact same thing if I write "no-cors" instead of "cors"
fetch(urlbittrexbtcusd,{ mode: "cors"})
.then(function(response) {
if(response.status == 200) { // Check if response went through
response.json().then(function(data) {
console.log(data);
bittrexbtcusdprice = parseFloat(data.result.last).toFixed(2);
});
} else { // Response wasn't ok. Check dev tools
console.log("response failed?");
console.log(response);
}
});
I've read this article, but can't figure out what it tries to achieve and how to plug my fetch to its code... https://www.html5rocks.com/en/tutorials/cors/
I don't understand what is "method" referring to, in his example.
I'm on an FTP and not on my server.
Fetch is a bit tricky. Fetch() won't even try making a request if mode is not "no-cors" but if you set mode: "no-cors" then the browser won't send all headers, it will only send "deemed safe" headers, that's what probably happening. So the problem is the combination of both fetch and browser peculiarities.
Here is the link to fetch specs

Angular 4 No 'Access-Control-Allow-Origin' header is present on the requested resource Bittrex [duplicate]

Json issues with javascript and jquery.
Trying to load some JSON using javascript.
I have it working using:
See it here: http://jsfiddle.net/5pjha/789/
var url = "http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=true";
$.getJSON(url, function (json) {
alert(JSON.stringify(json.results));
});
But it dosnt work on the following urls, why is this?
https://poloniex.com/public?command=return24hVolume
https://bittrex.com/api/v1/public/getmarkets
https://api.mintpal.com/v1/market/summary/
Are the following urls not correct JSON ?
Thanks
The google's api set the Access-Control-Allow-Origin header to *, so you could access it by cross domain.
While other urls you provided do not, so you will got an error like below:
XMLHttpRequest cannot load https://api.mintpal.com/v1/market/summary/.
No 'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://fiddle.jshell.net' is therefore not allowed
access.
I believe the issue is down to whether or not the servers you are requesting your JSON from have cross-origin resource sharing (CORS) enabled.
you can see in the headers from the google service that they set Access-Control-Allow-Origin:* This is not the case for teh other URL's you list.
To get around this you will need some form of proxy so that you can request from a server either on the same domain or a server that enables CORS.
For ajax request to any server, You need to define Access-Control-Allow-Origin header for client. which is absent in given. You need to define origin of XMLHttp request in server who can request.
For more info refer this link

Categories

Resources