Outils pour utilisateurs

Outils du site


web:javascript:web-api

Fetch API

Forme de base:

const response = await fetch(urlOrRequest[, options]);

Le premier argument URL ou request (objet) est obligatoire. Les options sont optionnels.

Options de base:

  • option.method: GET par default, peut être d'autres verbes HTTP.
  • option.body
  • option.headers

GET JSON data

async function loadNames() {
  const response = await fetch('/api/names');
  const names = await response.json();
 
  console.log(names); // [{ name: 'Joe'}, { name: 'Jane' }]
}
 
loadNames();

Explicitement demander du JSON

const response = await fetch('/api/names', {
  headers: {'Accept': 'application/json'}
});

POST JSON data

async function postName() {
  const object = { name: 'James Gordon' };
  const response = await fetch('/api/names', {
    method: 'POST',    body: JSON.stringify(object)  });

  const responseText = await response.text();
  console.log(responseText); // logs 'OK'
}

postName();

Pour spécifier qu'on envoie du JSON:

  body: JSON.stringify(object),  headers: {    'Content-Type': 'application/json'  }

Objet request

const object = { name: 'James Gordon' };
 
const request = new Request('/api/names', {
  method: 'POST',
  body: JSON.stringify(object),
  headers: {
    'Content-Type': 'application/json'
  }
});
 
const response = await fetch(request);
web/javascript/web-api.txt · Dernière modification : 2022/02/02 00:42 de 127.0.0.1