3

I made XMLHttpRequest get a json value from a server using this code:

let xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    let msg = JSON.parse(xhr.responseText);
    // Send the request to our POST Servlet
  }
};

xhr.open("GET", "/libs/granite/csrf/token.json", true);
xhr.send();

However, I want to use fetch in my code, however, upon trying the code below, I was instantly answered with a 403 error:

fetch("/libs/granite/csrf/token.json", { method: "GET" })
.then((response: any) => {
  if (response.status === 200 || response.statusText === "OK") {
    callback(ResponseCode.SUCCESS);
  } else {
    callback(ResponseCode.ERROR);
  }
})
.catch((error: any) => {
  callback(ResponseCode.ERROR);
});

I want to know the difference between the two and what should I modify to make the fetch work.

2
  • We can't see the server side code that determines what the status of the response should be. If you want to see the difference between the requests, look at the Network tab in your browser's developer tools.
    – Quentin
    Mar 20, 2017 at 7:18
  • 1
    @Quentin I looked through the network tab and the only difference I saw was their type, one is xhr and the other was, well, fetch. Mar 20, 2017 at 7:29

1 Answer 1

5

If there is credential validation on the server side then it could be failing because fetch does not send or receive cookies. You'll have to do -

credentials:'include'

Within your fetch request, as per the mozilla documents on Fetch

By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials header must be sent).

https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.