Basic use fetch ---

A, fetch

    An alternative scheme is to fetch the XMLHttpRequest ajax addition to obtaining background data fetch outer We can also use them at work, instead ajax Axios

 

Second, the installation

    

Implementation of npm install whatwg-fetch --save to install.

For compatibility with older browsers, you also need to install npm install es6-promise --save



Third, the basic use of fetch

npm install whatwg-fetch --savenpm install es6-promise --saveimport 'es6-promise'import 'whatwg-fetch'
fetch(url,options).then((res)=>{ console.log(res);},function(err){ console.log(err)})

Description:

    1, fetch the return value of the object is a promise

 

    2、options

        method: HTTP request mode, the default is GET

 

        body: request parameters

        fetch('/xxx', {

               method: 'post',

               body:'username=zhangsan&age=17'

 

       });

 

        headers: HTTP request header

            Because JSON data format is generally used, so to set ContentType application / json

 

            credentials: The default is omit, ignore the meaning, that is, without a cookie there are two parameters, same-origin, meaning that homologous request with cookie; include, indicate whether or cross-domain requests are homologous with cookie

 

 

    3, in response .then treated inside the first callback

 

        status (number): HTTP status code returned, the range between 100-599

 

        statusText (String): text description of the status returned by the server

 

        headers: HTTP header request returns

 

        body: Returns the body, there are some ways the processing returns body

 

        text (): returns a string-processing type

 

       json (): returns, and JSON.parse (responseText) as

 

       blob (): returns a Blob, Blob object is a binary data file of a class can not be changed

If the request is an XML format file, the call response.text. If the request pictures, using the method response.blob

 

note:

cookie delivery

Credentials must be added inside the header parameters: 'include', as will xhr as the current request to the cookies to

 

 

Four, get, post request method

    1、get

var result = fetch('url', {        credentials: 'include',        headers: {            'Accept': 'application/json, text/plain, */*',        },     });

 

    2、post

var result = fetch('/api/post', {        method: 'POST',        credentials: 'include',        headers: {            'Accept': 'application/json, text/plain, */*',            'Content-Type': 'application/x-www-form-urlencoded'        },        // 注意 post 时候参数的形式        body: "a=100&b=200"    });

 

V. get and post encapsulation methods

    1、http.get()

import 'es6-promise'import 'whatwg-fetch'
export default (url)=>({    var result = fetch(url, { credentials: 'include', headers: { 'Accept': 'application/json, text/plain, */*', },    })   .then(res=>res.json()); return result})

    2、http.post

import 'es6-promise'import 'whatwg-fetch'import qs from 'qs';export default (url,data)=>({    var result = fetch(url, {        method: 'POST',        credentials: 'include',        headers: {            'Accept': 'application/json, text/plain, */*',            'Content-Type': 'application/x-www-form-urlencoded'        },        // 注意 post 时候参数的形式        body: qs(data)    })    .then(res=>res.json())        return result;})

 

 

Six difference, fetch and axios of

 

axios("http://xxx/xxx.json?a=123'").then((res)=>{     console.log(res)//这里的r是响应结果})
fetch("http://www.baidu.com").then((res)=>{        console.log(res);//是一个综合各种方法的对象,并不是请求的数据})

 

 

fetch returns an unprocessed set of methods, types of data we can get what we want by these methods. If we want to json format, on the implementation of response.json (), if we want to string it response.text ()

 

axios 

        1, from the browser to create XMLHttpRequest

        2, http requests sent from node.js

        3, support for Promise API

        4, to intercept the request and response

        5, request and response data conversion

        6, the data is automatically converted JSON

        7, client support to prevent CSRF / XSRF

 

fetch:

    In line with separation of concerns, no input, output, and status tracking of events mixed in one object in

    More bottom, rich API provided (request, response)

    Out of the XHR, ES is the norm in the implementation of the new

 

1, fetchtch only given to the network a request, 400, 500 are of a successful request as required to handle the package

 

2, fetch default will not take cookie, you need to add configuration items

 

3, fetch does not support abort, does not support time-out control, the use of real setTimeout and Promise.reject

Now timeout control does not prevent the request process continues to run in the background, causing the amount of waste

 

4, fetch no way to monitor the progress of native request, and can XHR

 

Guess you like

Origin www.cnblogs.com/lijinxiao/p/11440780.html