Skip to content

Instantly share code, notes, and snippets.

@hedleysmith
Created August 12, 2016 15:00
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hedleysmith/15fa60fda5ef4369636a4b23e018dc8f to your computer and use it in GitHub Desktop.
Save hedleysmith/15fa60fda5ef4369636a4b23e018dc8f to your computer and use it in GitHub Desktop.
HTTP requests three ways - Fetch API vs jQuery.ajax vs Superagent
/*
* 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;
}
}
@krishnasaga
Copy link

Hi nice gist
Could you demonstrate how to parse and process json as a stream ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment