Skip to content

Instantly share code, notes, and snippets.

@prof3ssorSt3v3
Created July 21, 2017 21:41
Show Gist options
  • Save prof3ssorSt3v3/8ffde2dd0e14dbe2d8469a52f472c3a7 to your computer and use it in GitHub Desktop.
Save prof3ssorSt3v3/8ffde2dd0e14dbe2d8469a52f472c3a7 to your computer and use it in GitHub Desktop.
//basic fetch
//using jsonplaceholder for the data
//Remember that fetch returns a promise
//HTTP status codes - http://www.restapitutorial.com/httpstatuscodes.html
//to test with NODE we need to install the node-fetch package
// npm install node-fetch
//let fetch = require('node-fetch');
//get the details for a random user
const root = 'http://jsonplaceholder.typicode.com';
let id = Math.floor(Math.random() * 20) + 1; //id 1 to 20
let uri = root + '/users/' + id;
console.log('FETCH: ', uri);
//any user id higher than 10 will generate a 404 error
fetch( uri )
.then( function( response ){
if(response.status == 200){
return response.json();
}else{
throw new Error('Invalid user ID');
}
})
.then( (data) =>{
console.log( data );
let jsonData = JSON.stringify(data);
console.log(data);
let output = document.getElementById('output');
output.textContent = jsonData;
} )
.catch( (err)=>{
console.log('ERROR: ', err.message);
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment