Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a fetch request causes server to return 403 while XMLHttpRequest does not?

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.

like image 820
JD Hernandez Avatar asked Nov 01 '25 00:11

JD Hernandez


1 Answers

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

like image 160
Cook_arl Avatar answered Nov 03 '25 17:11

Cook_arl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!