-2

In my header, I will send token for authentication to my back-end but I don't know how I can add header to get method ..

    fetch('https://api.github.com/users/mralexgray/repos', {
    method: 'GET',
    headers: {
      "Content-Type":"application/json",
      "Accept": "application/json",
      "X-Aequseted-With": "XMLHttpRequest",
      "X-CSRF-TOKEN": token
    }
  }).then(result => {
    return result.json()
}).catch(err => {
    console.error(err);
});

in post method is clear, but in get method I have to get data from backend

Ahmet Emre Kilinc
  • 5,489
  • 12
  • 30
  • 42
Ali Ratel
  • 1
  • 3
  • The code you posted does add headers - what's the actual issue? by the way, is `X-Aequseted-With` a really bad typo of `X-Requested-With`? – Jaromanda X Sep 19 '22 at 05:16
  • looking at the pre-flight response, only the following headers are allowed `Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, Accept-Encoding, X-GitHub-OTP, X-Requested-With, User-Agent, GraphQL-Features` - so, a) that typo will fail the request, but since `x-csrf-token` isn't allowed, that too will fail the request - perhaps the token should be put in an Authorization header – Jaromanda X Sep 19 '22 at 05:20
  • at a guess, you need `"Authorization": \`Bearer ${token}\`` and fix the typo for `x-requested-with` and remove the `x-csrf-token` – Jaromanda X Sep 19 '22 at 05:22

1 Answers1

-1

You can try it out this way,

var myHeaders = new Headers();
myHeaders.append("User-Agent", "PostmanRuntime/7.29.2");

var requestOptions = {
  method: 'GET',
  headers: myHeaders,
  redirect: 'follow'
};

fetch("http://api.github.com/users", requestOptions)
  .then(response => response.text())
  .then(result => console.log(result))
  .catch(error => console.log('error', error));

As I am a Frontend Developer I use postman to handle and structure all sorts of fetching code. you can try it out as well. Might solve your issue.