js fetch with headers code example

Example 1: fetch json post

(async () => {
  const rawResponse = await fetch('https://httpbin.org/post', {
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({a: 1, b: 'Textual content'})
  });
  const content = await rawResponse.json();

  console.log(content);
})();

Example 2: js fetch 'post' json

//Obj of data to send in future like a dummyDb
const data = { username: 'example' };

//POST request with body equal on data in JSON format
fetch('https://example.com/profile', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
})
.then((response) => response.json())
//Then with the data from the response in JSON...
.then((data) => {
  console.log('Success:', data);
})
//Then with the error genereted...
.catch((error) => {
  console.error('Error:', error);
});

//																		Yeah

Example 3: Add no cores to fetch

// There were no quick access to mode and credentials to other fetch answers.
// Data you'll be sending
const data = { funny: "Absolutely not", educational: "yas" }

fetch('https://example.com/api/', {
  method: 'POST', // The method
  mode: 'no-cors', // It can be no-cors, cors, same-origin
  credentials: 'same-origin', // It can be include, same-origin, omit
  headers: {
    'Content-Type': 'application/json', // Your headers
  },
  body: JSON.stringify(data),
}).then(returnedData => {
  // Do whatever with returnedData
}).catch(err => {
  // In case it errors.
})

Example 4: javascript fetch api post

fetch('https://example.com/profile', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({
  	'foo': 'bar'
  }),
})
  .then((res) => res.json())
  .then((data) => {
    // Do some stuff ...
  })
  .catch((err) => console.log(err));

Example 5: fetch api javascript

fetch('https://apiYouWantToFetch.com/players') // returns a promise
  .then(response => response.json()) // converting promise to JSON
  .then(players => console.log(players)) // console.log to view the response

Tags:

Misc Example