Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const fetch = require('node-fetch');
- const defaultURL = 'https://api.randomuser.me/';
- // request -- startline, headers, and body
- const getRequestInit = {
- method: 'GET', // *GET, POST, PUT, DELETE, etc.
- mode: 'cors', // no-cors, cors, *same-origin
- cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
- credentials: 'same-origin', // include, *same-origin, omit
- headers: {
- 'Content-Type': 'application/json',
- // 'Content-Type': 'application/x-www-form-urlencoded',
- },
- redirect: 'follow', // manual, *follow, error
- referrer: 'no-referrer', // no-referrer, *client
- //body: JSON.stringify(data), // body data type must match "Content-Type" header
- }
- const handleErrors = (response) => {
- // Can handle response.status codes, but this is very basic implimentation
- if (!response.ok) throw Error(response.status);
- return response;
- }
- // First implimentation with promises. -- Least favorite
- function getData(url = defaultURL) {
- // Fetch data with url parameter, and request info.
- return fetch(url, getRequestInit)
- .then(handleErrors)
- .then( (response) => {
- return response.json();
- })
- .catch( (error) => {
- console.log("Error fetching random users: ", error.message);
- });
- };
- // Async and Await implimentation -- My favorite
- const getDataASync = async (url = defaultURL) => {
- try {
- const response = await fetch(url, getRequestInit);
- const { results } = await response.json();
- return results;
- } catch(error) {
- //Do magic error stuff
- console.log("Error fetching random users: ", error.message);
- }
- };
- // Async and Await implimentation -- Second favorite
- const getDataAsyncTwo = async (url = defaultURL) => {
- return await fetch(url, getRequestInit)
- .then(handleErrors)
- .then( async (response) => {
- let { results } = await response.json();
- return results;
- })
- .catch((error) => {
- console.log("Error fetching random users: ", error.message);
- })
- };
- // Execute fetching arbritrary user data
- //getData().then( (data) => console.log(data.results) );
- getDataASync().then((data) => console.log(data));
- //getDataAsyncTwo().then( (data) => console.log(data));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement