Answers for "javascript fetch syntax"

35

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
Posted by: Guest on March-28-2020
6

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));
Posted by: Guest on July-14-2020
4

how to use fetch() javascript

//Most API's will only allow you to fetch on their website.
//This means you couldn't run this code in the console on 
// google.com because:
// 		1. Google demands the fetch request be from https
// 		2. open-notify's API blocks the request outside of their website

fetch('http://api.open-notify.org/astros.json')
.then(function(response) {
  return response.json();
})
.then(function(json) {
  console.log(json)
});

// Here is another example. A method (function) that 
// grabs Game of Thrones books from an API ...

function fetchBooks() {
  return fetch('https://anapioficeandfire.com/api/books')
  .then(resp => resp.json())
  .then(json => renderBooks(json));
}

function renderBooks(json) {
  const main = document.querySelector('main')
  json.forEach(book => {
    const h2 = document.createElement('h2')
    h2.innerHTML = `<h2>${book.name}</h2>`
    main.appendChild(h2)
  })
}

document.addEventListener('DOMContentLoaded', function() {
  fetchBooks()
})
Posted by: Guest on March-30-2020
4

fetch suntax

fetch('http://example.com/movies.json')
  .then((response) => {
    return response.json();
  })
  .then((data) => {
    console.log(data);
  });
Posted by: Guest on March-16-2020
0

what is fetch javascript

/*
The fetch() method in JavaScript is used to request
to the server and load the information in the webpages.
The request can be of any APIs that returns the data of the format JSON or XML.
This method returns a promise.
*/

//Syntax:
fetch( url, options )
/*
URL: It is the URL to which the request is to be made.
Options: It is an array of properties. It is an optional parameter.
*/
Posted by: Guest on September-15-2021

Code answers related to "Javascript"

Browse Popular Code Answers by Language