how to add header to fetch GET method

1.8k Views Asked by At

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

1

There are 1 best solutions below

0
AkhlakHossain Jim On

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.