Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disabling CORS using js fetch [duplicate]

Tags:

javascript

I've looked into it and my syntax looks correct but I can't figure out what is going wrong. If I didn't include the options params, everything works fine except CORS is on, which is what I do not want.

After adding the options with mode in the request, I am now getting this error with all requested images:

image-cropper-modal.js:73 GET data: net::ERR_INVALID_URL

have already tried looking here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch and here: https://jakearchibald.com/2015/thats-so-fetch/

Here is my code:

const options = {
  method: 'GET',
  mode: 'no-cors'
};

fetch(url, options).then(response => response.blob())
   .then(blob => {
      let reader = new FileReader();
      reader.onload = () => {
        const type = blob.type;
        const [image, dataUrl] = [new Image(), reader.result];
        image.src = dataUrl;
        const [width, height] = [image.width, image.height];
        const {minWidth, minHeight} = props.opt;
        const isWithinBounds = (width >= minWidth) && (height >= minHeight);
        callback({
          dataUrl,
          height,
          minHeight,
          minWidth,
          width
        });
   }
   reader.readAsDataURL(blob) 
});
like image 539
Anchalee Avatar asked Dec 08 '16 01:12

Anchalee


1 Answers

Using the no-cors option will not give you a readable response:

no-cors — Prevents the method from being anything other than HEAD, GET or POST. If any ServiceWorkers intercept these requests, they may not add or override any headers except for these. In addition, JavaScript may not access any properties of the resulting Response. This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains. (source, emphasis mine)

In other words, if you want to make a request from JavaScript, you need to have CORS enabled. If you can't set up CORS support on the server yourself, the only way around this is to proxy your request through a server makes non-CORS requests on your behalf (either by using up your own server, or by using a third-party service such as crossorigin.me or cors-anywhere, or any of a bunch of other similar services).

For context, the no-cors option is available because there are some cases where you may want to make a non-CORS request without having to be able to read the response. For instance, service workers can use this option to intercept (e.g., redirect or cache, but not read or modify) requests made by the browser (like <img> tags or HTML pages, not just JavaScript code).

like image 136
Frxstrem Avatar answered Sep 19 '22 07:09

Frxstrem