0

To make things simpler to understand, consider the below code:

<script type="text/javascript">
  var subscriberId = '12345';
</script>
<script type="text/javascript" src="https://example.com/main.js"></script>

What im trying to achieve, is how to create the same behavior of the above code, using the fetch api. Im using Google AMP, so this is won't validate. What im currently trying to do, is to create a service worker instead, and to run JavaScript from there. In a normal html page the above snippet would return a response from the remote server (i tried it and verified it), with a json object which is visible in "XHR and Fetch" in chrome dev tools. The thing is that due to cors policy, i can not use POST, but only(?) GET. So i came up with the code below:

function validateResponse(response) {
  if (!response.ok) {
    throw Error(response.statusText);
  }
  return response;
}

function readResponse(response) {
  return response();
}
function logResult(result) {
  console.log(result);
}

function logError(error) {
  console.log('Looks like there was a problem: \n', error);
}
function fetchUrl(pathToResource) {
  fetch(pathToResource, {
  method: "GET",
  mode: 'no-cors',
  credentials :'include',
  headers: new Headers({
  'Accept': 'text/html',
  'Content-Type': 'application/javascript;charset=UTF-8',
  'Cache': 'no-cache',
  'subscriberId': '12345'
   }),
})
  .then(validateResponse)
  .then(readResponse)
  .then(logResult)
  .catch(logError);
}

fetchUrl('https://example.com/main.js');

And i receive in the console

Looks like there was a problem: 
 Error
    at validateResponse

Can someone provide some insights to the problem? Obviously this is an opaque response, and i don't know how to deal with it.

Skeptic
  • 1,254
  • 14
  • 18
  • If you use mode: 'no-cors', then you can’t read the response. That’s what “opaque” means. So whatever 'validateResponse' is trying to do, it’s not going to work — because by setting mode: 'no-cors', you’re explicitly asking the browser to block your code from any access to reading the response body or response headers. – sideshowbarker Nov 09 '18 at 01:32
  • 1
    Opaque responses are useless outside service-workers. If you are using it with the Cache-API then all you can do is cache the response. – mpm Nov 09 '18 at 01:36
  • @sideshowbarker is there any workaround to this? Googling around, some people mentioned the use of a proxy server, but i have no idea how to do this, and also how effective it will be. – Skeptic Nov 09 '18 at 03:58
  • See the *How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems* section of the answer at https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 – sideshowbarker Nov 09 '18 at 04:07
  • Noted. I managed to bypass the problem by using a helper i-frame for the time being at least. – Skeptic Nov 09 '18 at 21:19

0 Answers0