[SOLVED] add header to fetch GET method

Issue

This Content is from Stack Overflow. Question asked by Ali Ratel

I have a problem in fetch data ?
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',
  header: {
    "Content-Type": "application/json",
    "Accept": "application/json",
    "X-Aequseted-With": "XMLHttpRequest",
    "Authorization": `Bearer ${token}`
  }
}).then((result) => {
  result.json()
  console.log(result)
  if (result.status == 200) {
    async function GetLink() {
      const response = await fetch('https://api.github.com/users/mralexgray/repos')
      const data = await response.json();
      console.log(data)
      sessionStorage.setItem('userAttemps', data[0].id);
      sessionStorage.setItem('freeAttemps', data[0].id);
    }
    GetLink()
  }
}).catch(err => {
  console.error(err);
});
userAttemps = sessionStorage.getItem('userAttemps')
freeAttemps = sessionStorage.getItem('freeAttemps')

Is my code correct?



Solution

// Example POST method implementation:
async function postData(url = '', data = {}) {
  // Default options are marked with *
  const response = await fetch(url, {
    method: 'POST', // *GET, POST, PUT, DELETE, etc.
    mode: 'cors', // no-cors, *cors, same-origin
    cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
    credentials: 'same-origin', // include, *same-origin, omit
    headers: {
      'Content-Type': 'application/json'
      // 'Content-Type': 'application/x-www-form-urlencoded',
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return response.json(); // parses JSON response into native JavaScript objects
}

postData('https://example.com/answer', { answer: 42 })
  .then((data) => {
    console.log(data); // JSON data parsed by `data.json()` call
  });


This Question was asked in StackOverflow by Ali Ratel and Answered by Akash Sengar It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?