How to use FETCH API while using GET and set a non-header variable?

246 views Asked by At

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.

0

There are 0 answers