Fetch

Fetch

fetch对象接受1-2个参数,无论请求成功与否返回一个promise对象 用于处理ajax请求

Fetch 对象

GlobalFetch.fetch(url, options)

第一个参数是必要的,传入要请求的路径

第二个参数可选,即fetch对象进行请求时的一些配置,类似Request对象,包括

  • method

  • url

  • headers

  • referrer

  • mode

  • redirect

  • cache

使用方式

链式处理

fetch(url, option)
    .then(functionresponse){})
    .catch(functionerror){})

或者是

var request = new Request();
fetch(request).then ...

Request 对象

doc

new Request(url, option)

第一个参数为url

第二个参数为option,缺省设置,默认方法为get,mode为cors(fetch的配置与Request基本一致)

var request = new Request('/users.json', {
    method: 'POST', 
    mode: 'cors', 
    redirect: 'follow',
    headers: new Headers({
        'Content-Type': 'text/plain'
    })
});

fetch(request).then(function() { /* handle response */ });

配置属性包括(所有的属性都是只读的,一经创建就无法修改)

  • method

  • url

  • headers

  • referrer

  • mode

  • redirect

  • cache

methods

  • clone

  • arrayBuffer

  • blob

  • formData

  • json

  • text

Headers 对象

// 创建一个空的 Headers 对象,注意是Headers,不是Header
var headers = new Headers();

// 添加(append)请求头信息
headers.append('Content-Type', 'text/plain');
headers.append('X-My-Custom-Header', 'CustomValue');

// 判断(has), 获取(get), 以及修改(set)请求头的值
headers.has('Content-Type'); // true
headers.get('Content-Type'); // "text/plain"
headers.set('Content-Type', 'application/json');

// 删除某条请求头信息(a header)
headers.delete('X-My-Custom-Header');

// 创建对象时设置初始化信息
var headers = new Headers({
    'Content-Type': 'text/plain',
    'X-My-Custom-Header': 'CustomValue'
});

methods

  • append

  • has

  • get

  • set

  • delete

Response 对象

Last updated