Front-end engineers fetch four common mistakes (translation)

View original  

fetch The browser is the most popular way to send http request. It is not just a specific XMLHttpRequest better, more in line with ergonomic API, it also brought a lot of exciting new features, such as the response stream, more control over documents and CORS requests, as well as with ServiceWorkers and cache the integrated API

I also study and use it, but also witnessed fetch growth (Original: widely used), we found that even experienced developers will make some of the more common mistakes. I think in large part to fetch it looks like it's behavior patterns are like the jQuery API on the surface of  $ .ajax , AngularJS of $ HTTP , Axios and so on. There are some important differences between them, and most of these differences from fetch prototype as the underlying network requests

1. http think that once an error occurs, promise will be reject

Fetch is based on the promise, and therefore relatively easy to think, if the server returns http error status code , like 404 or 500, Promise will be rejected, just like the original XMLHttpRequest; but fetch is not the case - it's just the occurrence of "network error (network error)" will be rejected (this is a confusing term, but the specification says so). If the server get http error status, it indicates that the server is working correctly and in dealing with requests, "network error (network error)" indicates that simply can not reach the server (such as connection refused or name does not resolve) or request configuration errors (Bad Request address).

For example, the  ftpprotocol does not support fetch, so it will be rejected a return of promise:

fetch('ftp://example.com')  .catch(err => console.error('Caught error: ', err))复制代码

However, a request URL and return a 404 error occurs or not an error (ie, similar to 404 such errors fetch returns are not rejected)

fetch('https://jsonplaceholder.typicode.com/404') 
 .then(res => console.log('response: ', res))  .catch(console.error)复制代码

I think for most developers, the promise of a return error http rejected is very useful for web application processing. To this end (fetch handling of http error), we only need to verify the  ok  value of the property, if  ok

Value false, then reject

fetch('https://jsonplaceholder.typicode.com/404')  
    .then(res => {    
        if(res.ok) {      
             return res;    
        } else {      
             throw Error(`Request rejected with status ${res.status}`);   
     }})  
    .catch(console.error)复制代码


2. forget to include credentials

And XHR different, fetch request does not include any of the cookie by default. So, if you need a cookie-based authorization request for your API's (most web applications need), you must have this option, or your call may return 401 unauthorized.

This is very simple:

fetch('/url', { credentials: 'include' })复制代码

Note that if you are using fetch polyfill, then (unfortunately) you might occasionally forget that everything looks as if you already are using credentials: 'include'the same, because it simply uses XHR on the ground floor and have it automatically XHR kind of behavior.

3. forget to set `Content-Type` to` application / json` upload JSON 

$ Http, axios http and other tools will be set this header for you by default, so it is easy to forget.

fetch('https://cameronnokes.com/slack-ron-swanson-quote-bot/ron', {
   method: 'POST',   
   body: JSON.stringify({text: 'bacon'}),  
   headers: {'Content-Type': 'application/json'}})
   .then(res => res.json())
   .then(console.log)复制代码

If you do not include this header, the server may return a 400number Bad Request, because endpointnot support the plain text content types, or can not handle the body of this text, depending on the implementation of the API. In any case, your API may return HTTP error status.

4. string manually splice a complex query parameters

I often see code like this:

fetch('/endpoint?foo=${n > 1 ? 123 : 456}&bar=abc&query=${encodeURIComponent(someString || '')}复制代码

This is not entirely bad, but I think if we let the new class and a small amount of URLSearchParams lodash to do more work for us, it will be easier to read, less error prone.


URLSearchParams great class, encoding correctly handle, connecting the object to a String like. I think it is easier to read and maintain.

to sum up:

Fetch great, but you want to enjoy responsibly


======================= ====================== add the following to the translator ===

Accompanied fetch the advent and development, currently fetch more and more to use in a production environment enterprises. The open source community about fetch polyfilll have a variety of options, but also because based Promise, the following can be the perfect solution to their compatibility issues (especially IE), reference only:

  • 由于 IE8 是 ES3,需要引入 ES5Of polyfill: es5-shim,es5-sham

  • The introduction Promiseof polyfill:es6-promise

  • The introduction of fetchthe probe library:fetch-detector

  • The introduction fetchof polyfill:fetch-ie8

  • Optional: If you used the jsonpintroduction offetch-jsonp

  • Optional: Turn Babelthe runtimemode, now use async/await

fetch  benefits Needless language, but there are some problems fetch, for example, does not support timeout, does not support the progress, especially with the traditional fetch cross-domain issues on the difference between cross-domain approach, the community are corresponding solutions, this Wen name a few. As forgive the authors put it: responsibly to enjoy



Reproduced in: https: //juejin.im/post/5cebc4d2f265da1bc37eed52

Guess you like

Origin blog.csdn.net/weixin_33757911/article/details/91436635