About us

Join us FREE!

How do I add headers for requests from an API?

Tutorial by Er Satya connectclue-author-image

All > Tech Blogger | Java | Spring Boot | HTML | CSS | MySQL > Java | Spring Boot

1 like

Please login to like this article.

connectclue-linkedin-share

How do I add headers for requests from an API?


The sample code:

// 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'
    
    },
    redirect: 'follow', // manual, *follow, error
    referrerPolicy: 'no-referrer', // no-referrer
    body: JSON.stringify(data) // body data type must match "Content-Type" header
  });
  return await response.json(); // parses JSON response into native JavaScript objects
}

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


 implementation based on the code above:

fetch(url, {
        headers: {
            "User-Agent": "MyAppName/Version# (Language=Javascript; Platform: Linux)"
        }
    }).then(function(resp) {
        return resp.json();
    }).then(function(data){...


connectclue-linkedin-share

More articles:


Recent lost & found:


Login for enhanced experience

connectclue-tick Create and manage your profile

connectclue-tick Refer an author and get bonus Learn more

connectclue-tick Publish any lost and found belongings

connectclue-tick Connect with the authors & add your review comments

connectclue-tick Join us for Free to advertise for your business or Contact-us for more details

connectclue-tick Join us for Free to publish your own blogs, articles or tutorials and get your Benefits

connectclue-login

Back to top