Created
August 12, 2016 15:00
-
-
Save hedleysmith/15fa60fda5ef4369636a4b23e018dc8f to your computer and use it in GitHub Desktop.
HTTP requests three ways - Fetch API vs jQuery.ajax vs Superagent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* Client-side HTTP requests three ways, using ES6 syntax. | |
* 1. jQuery.ajax() | |
* 2. Superagent | |
* 3. Fetch API | |
* 4. Bonus helper | |
*/ | |
// 1. jQuery.ajax() | |
// http://api.jquery.com/jquery.ajax/ | |
import jquery from 'jquery'; | |
jquery.ajax({ | |
method: "GET", | |
url: 'https://jsonplaceholder.typicode.com/users', | |
headers: { | |
'custom-head': 'custom ', | |
}, | |
}) | |
.done((result) => { | |
console.log(result); | |
}) | |
.fail((jqXHR, textStatus, error) => { | |
console.log(textStatus); | |
}); | |
// 2. Superagent | |
// https://github.com/visionmedia/superagent | |
import request from 'superagent'; | |
request | |
.get('https://jsonplaceholder.typicode.com/users') | |
.set('custom-header', 'custom header value') | |
.end((error, response) => { | |
if (error) { | |
console.log(error); | |
} else { | |
console.log(response.body); | |
} | |
}); | |
// 3. Fetch API | |
// 'isomorphic-fetch' is optional. It will include a [Fetch API polyfill](https://github.com/github/fetch) | |
// [if needed](http://caniuse.com/#feat=fetch) (e.g for IE). | |
import fetch from 'isomorphic-fetch'; | |
fetch('https://messaging.settled.co.uk/debug') | |
.then(response => { | |
// This response from a server could contain a HTTP error code but it will | |
// still end up here. To throw this as an error see checkFetchStatus() below | |
// and uncomment the following: | |
// checkFetchStatus(response) | |
console.log(response); | |
}) | |
.catch(error => { | |
// Network or timeout error. | |
console.log(error); | |
}); | |
// 4. Bonus: Fetch API respnse status check helper | |
/** | |
* Check the status of a returned Fetch API call and throw an error if the | |
* server returns an error code. | |
* See https://www.tjvantoll.com/2015/09/13/fetch-and-errors/ | |
*/ | |
function checkFetchStatus(response) { | |
if (response.status >= 200 && response.status < 300) { | |
return response; | |
} else { | |
const error = new Error(response.statusText); | |
error.response = response; | |
throw error; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi nice gist
Could you demonstrate how to parse and process json as a stream ?