-1

(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?

Marco Scarnatto
  • 117
  • 1
  • 9
  • You have to allow CORS this shoud be set in your API settings. https://itnext.io/cors-understanding-it-practically-9c401ed818cd – MrLine Feb 08 '19 at 12:44
  • But I do not have access to change anything at http://serverCDN !! The change I understand should be made, on the remote server (to which I am accessing) is it correct? – Marco Scarnatto Feb 08 '19 at 14:34
  • I understand the **CORS** problem. But ... my specific doubt, is because the first block of code **DOES IT WORK**? Is not that also javascript? – Marco Scarnatto Feb 08 '19 at 14:43
  • The reason for the difference is that browsers don’t enforce the same-origin policy on on the img src attribute, but browsers do enforce the same origin policy on fetch requests (unless the server response opts into relaxing the same-origin policy, by including the Access-Control-Allow-Origin header in the response). – sideshowbarker Mar 04 '19 at 01:10

1 Answers1

0

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

alpham8
  • 1,314
  • 2
  • 14
  • 32
  • But I do not have access to change anything at http://serverCDN !!! The change I understand should be made, on the remote server (to which I am accessing) is it correct? JSONP could be an option – Marco Scarnatto Feb 08 '19 at 14:39