paint-brush
[Nodejs][React] Isomorphic-Fetch: the suspicious partby@peterchang_82818
9,876 reads
9,876 reads

[Nodejs][React] Isomorphic-Fetch: the suspicious part

by April 20th, 2017
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

I am sure that every<strong><em> ‘isomorphic developer’ </em></strong>must have heard about the magic function<em> isomorphic-fetch</em>, which is implementation of sending API request for both <em>Node.js</em> and <em>Browser</em>.

Company Mentioned

Mention Thumbnail
featured image - [Nodejs][React] Isomorphic-Fetch: the suspicious part
 HackerNoon profile picture

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.

Introduction of isomorphic-fetch

To install

$ 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

Tricky part of isomorphic-fetch

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 :

  1. response text with 200 status code
  2. response json with 200 status code
  3. response text with 400 status code
  4. response json with 400 status code
  5. response whatever result in a certain long time (timeout)

To found out what is actually happening inside fetch() when I use the incorrect method to handle those situation.

1. Parsing text response by response.json( )

It goes to exception

2. Parsing json response by response.text( )

It responses as String type

3. Impossible in timeout handling

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.

Reference:

https://www.npmjs.com/package/isomorphic-fetch

https://github.com/wahengchang/isomorphicfetch-must-know