I am sure that every ‘isomorphic developer’ must have heard about the magic function isomorphic-fetch, which is implementation of sending API request for both Node.js and Browser.
Write once use both sides, Server and Browser
To checkout how these tests are implemented go and clone the repository from git.
$ npm install --save isomorphic-fetch es6-promise
and import it in the entry of Node.js server
require('es6-promise').polyfill();require('isomorphic-fetch');
The proper way to use fetch(), using resposne.text() to parse text response , and resposne.json() to parse json response from the server:
text response
json response
As my experience, fetch() is so easy to use and saves me so much time in building isomorphic website, however it is too quiet when there is error or exception is happening, takes me a lot of time to find out the bug.
The way I experimented fetch(), is creating a simple Express.js server, with 5 different situation :
To found out what is actually happening inside fetch() when I use the incorrect method to handle those situation.
It goes to exception
It responses as String type
fetch() does not support timeout handling, it could wait until we die and without a response. The walk around way is creating a timeoutPromise wrapper by ourself.
This is a solution suggested by @alcat2008 in the git issue:
var p = Promise.race([ fetch('/resource-that-may-take-a-while'), new Promise(function (resolve, reject) { setTimeout(() => reject(new Error('request timeout')), 5000) })])
p.then(response => console.log(response))p.catch(error => console.log(error))
Like this story? It is helpful to others? It helps me know if you’d like to see write more about his topic and helps people see the story, when tap the heart below.