Fetch!

+

Interceptors

Lee Blazek

Today!

  • About Me
  • Who are you?
  • Fetch
    • What is it?
    • Current support
    • What can it replace?
    • Basic usage
    • Customize options
    • Response processing
    • polyfills
    • future features
  • Interceptors
    • What are they?
    • Where did they come from?
    • Example
    • full projects
  • Demos
    • basic MDN
    • NG1.6.x

About Me

Angular, JS, Mean Stack, Front-end, Node api's, with a side of iOS

What other people say about me

- Jeeze... This guy is the Happy Gilmore of javascript + Web Development

What about you?

The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

 

This kind of functionality was previously achieved using XMLHttpRequest. Fetch provides a better alternative that can be easily used by other technologies such as Service Workers. Fetch also provides a single logical place to define other HTTP-related concepts such as CORS and extensions to HTTP.

- MDN

Fetch - What is it?

Current Support

Text

Replace Other request libraries

  • XMLHttpRequest
  • Angular
    • $http
    • $resource
    • angular-resitfy
  • react
    • axios
  • jquery.ajax..

Basic Usage

// 1
fetch('data.json')

// 2 
.then(response => {
  // response is response object not the actual data
  // extract content below
  return response.json();
})

// 3
.then(data => {
  //now do whatever with data
  data.forEach(thing => console.log(thing))
});

Custom Request


const init = {
      method: 'GET',
      headers: {
        customHeader: 1,
        Accept: 'application/json',
        Authorization: 'Bearer e49062f9-2fb8-405a-85d7-bdbba336d240',
      },
      mode: 'cors',
      cache: 'default'
    }


fetch('data.json', init)
.then(response => response.json())
.then(data => data.forEach(thing => console.log(thing)));

Response Objects

  1. Response.status — An integer (default value 200) containing the response status code.
  2. Response.statusText — A string (default value "OK"),which corresponds to the HTTP status code message.
  3. Response.ok — seen in use above, this is a shorthand for checking that status is in the range 200-299 inclusive. This returns a Boolean.

Response Objects


const init = {// ...}


fetch('data.json', init)
.then(response => {

    // response.ok — seen in use above, this is a shorthand 
    // for checking that status is in the range 200-299 inclusive. 
    // This returns a Boolean.

    if (Response.ok) {
        return response.json()    
    } 
    throw new Error('Network response was not ok.');
})
.then(data => data.forEach(thing => console.log(thing)));

Response Processing

Properties

  • Response.headers
  • Response.ok
  • Response.redirect
  • Response.status
  • Response.statusText
  • Response.type
  • Response.url
  • Response.useFinalUrl
  • Response.bodyUsed

Methods

  • Response.clone()
  • Response.error()
  • Response.arrayBuffer()
  • Response.blob()
  • Response.formData()
  • Response.json()
  • Response.text()

- https://developer.mozilla.org/en-US/docs/Web/API/Response

Polyfills

  • https://github.com/github/fetch
  • https://www.npmjs.com/package/isomorphic-fetch (both browser and server side)
  • https://github.com/camsong/fetch-ie8
  • https://www.npmjs.com/package/node-fetch-polyfill (for server side only)

Future Features

(don't try these at home kids)

  • fetchController
  • fetchObserver
  • fecthSignal

Notes

Note that the fetch specification differs from jQuery.ajax() in mainly two ways that bear keeping in mind:

  1. The Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing.
  2. By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

MDN DEMO's

Part 2 :

Interceptors

What's the interceptor concept?

In a nut shell its an http request middle ware for the browser like middle ware in a node express server app.

  • Add/remove headers, tokens, etc
  • Transform requests or repsonses
  • Manage and TEST all these in one file as opposed to every place a request is made
  • swap out settings per env easily
  • test different env's easily
  • have tracking requests managed and tested in one place

browser.pause()

  • "c" move to next task in que
  • "repl" to enter interactive mode and use element.all(), etc
  • "ctrl+c" to quit debugger

Where did the interceptor concept start?

Angular $http interceptors!!

-https://docs.angularjs.org/api/ng/service/$http

What's an Interceptor?

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests.

The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

 

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

There are two kinds of interceptors (and two kinds of rejection interceptors):

1. request: interceptors get called with a http config object. The function is free to modify the config object or create a new one. The function needs to return the config object directly, or a promise containing the config or a new config object.
2. requestError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.
3. response: interceptors get called with http response object. The function is free to modify the response object or create a new one. The function needs to return the response object directly, or as a promise containing the response or a new response object.
4. responseError: interceptor gets called when a previous interceptor threw an error or resolved with a rejection.

For purposes of global error handling, authentication, or any kind of synchronous or asynchronous pre-processing of request or postprocessing of responses, it is desirable to be able to intercept requests before they are handed to the server and responses before they are handed over to the application code that initiated these requests.

 

The interceptors leverage the promise APIs to fulfill this need for both synchronous and asynchronous pre-processing.

 

The interceptors are service factories that are registered with the $httpProvider by adding them to the $httpProvider.interceptors array. The factory is called and injected with dependencies (if specified) and returns the interceptor.

- https://docs.angularjs.org/api/ng/service/$http

Recent Packages

Demos

 

  1. demo angular 1.6.x app
  2. ng2
  3. mithril
  4. react

Lee Blazek

  • www.berzek.io
  • info@berzerk.io
  • linkedin: www.linkedin.com/in/leeblazek
  • https://github.com/berzerk-interactive

Fetch! - The New ES6 api

By Lee Blazek

Fetch! - The New ES6 api

  • 1,005