CURL avec JavaScript
https://developers.google.com/web/updates/2015/03/introduction-to-fetch
fetch(url) // Call the fetch function passing the url of the API as a parameter. Pas d'options: GET
.then(function(data) {
// Your code for handling the data you get from the API
})
.catch(function(e) {
console.error(e)
});
Traitement de la réponse
La réponse est un objet avec une série de méthodes: .blob(), .text() ou .json() ...
fetch(url)
.then((data) => data.json()) // Transform the data into json
.then(function(objet) {
// objet JSON
})
})
Envoi d'arguments
let data = {
name: 'Sara'
}
method
headers
body=data //objet JSON
Objet réponse
fetch('users.json').then(function(response) {
console.log(response.headers.get('Content-Type'));
console.log(response.headers.get('Date'));
console.log(response.status);
console.log(response.statusText);
console.log(response.type);
console.log(response.url);
});
var myHeaders = new Headers();
myHeaders.append("x-access-token", "goldapi-3qem6ukfijcdr6-io");
myHeaders.append("Content-Type", "application/json");
var requestOptions = {
method: 'GET',
headers: myHeaders,
redirect: 'follow'
};
fetch("https://www.goldapi.io/api/XAU/USD", requestOptions)
.then(response => response.text())
.then(result => console.log(result))
.catch(error => console.log('error', error));