美文网首页
fetch 的使用

fetch 的使用

作者: 琉璃橙子 | 来源:发表于2017-09-07 17:41 被阅读327次

现在应该很少有人用原生的JS内置XMLHttpRequest对象写异步调用了,仍然用的比较多的应该是Jquery的ajax方法,例如:

$.ajax({
   type: 'get',
   url: location.herf,
   success: function(data){
       console.log(data);
   }
})

最近写一个demo用到了fetch API,顿时觉得比ajax好用n倍,遂记录之。

fetch 介绍

fetch API 来源于 Promise ,可参见:Promise;

fetch的API 也可以参见:fetch;

fetch()方法调用两个参数:

fetch(input, init)

其中:
input

  • 定义要获取的资源。这可能是:一个 USVString 字符串,包含要获取资源的 URL。一些浏览器会接受 blob: 和 data:
  • 作为 schemes.一个 Request 对象。

input直白来说等于ajax中传入的url;

fetch()另一个参数 init可以配置其他请求相关参数,相当于ajax里的type,这个参数是可选的,包括:

method: 请求使用的方法,如 GET、POST.
headers: 请求的头信息,形式为 Headers 对象或 ByteString。
body: 请求的 body 信息,可能是一个 Blob、BufferSource、FormData、URLSearchParams 或者 USVString 对象。(如果是 GET 或 HEAD 方法,则不能包含 body 信息)
mode: 请求的模式,如 cors、 no-cors 或者 same-origin。
credentials: 请求的 credentials,如 omit、same-origin 或者 include。
cache: 请求的 cache 模式: default, no-store, reload, no-cache, force-cache, or only-if-cached。

fetch()的success callback 是用 .then()完成的,实际上按照我的理解,fetch()就是一个Promise对象的实例,Promise对象实例如下:

new Promise(
    /* executor */
    function(resolve, reject) {...}
);
var promise = new Promise(function(resolve, reject) {
  if (/* 异步操作成功 */){
    resolve(value);
  } else {
    reject(error);
  }
});

promise.then(function(value) {
  // success
}, function(value) {
  // failure
});

所以fetch()中,通过.then()调用异步成功函数resolve,通过.catch()调用异步失败函数reject;
拼装在一起,就有:

fetch(location.herf, {
    method: "get"
}).then(function(response) {
    return response.text()
}).then(function(data) {
    console.log(data)
}).catch(function(e) {
  console.log("Oops, error");
});

这其中,第一步.then()将异步数据处理为text,如果需要json数据,只需要 :

function(response) {return response.json()}

用es6箭头函数写,就是:

fetch(url).then(res => res.json())
  .then(data => console.log(data))
  .catch(e => console.log("Oops, error", e));

fetch 兼容性

所有的ie都不支持fetch()方法,所以,考虑兼容性,需要对fetch()使用polyfill;
使用Fetch Polyfil来实现 fetch 功能:

npm install whatwg-fetch --save

对于ie,还要引入Promise

npm install promise-polyfill --save-exact

考虑到跨域问题,需要使用Jsonp,那么还需要fetch-jsonp:

npm install fetch-jsonp

至此,则有:

import 'whatwg-fetch';
import Promise from 'promise-polyfill';
import fetchJsonp from 'fetch-jsonp';

fetchJsonp('/users.jsonp')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json', json)
  }).catch(function(ex) {
    console.log('parsing failed', ex)
  })

Ref:

相关文章

  • Fetch

    Fetch API使用 Fetch

  • JS--Fetch API

    fetch() 使用 Fetch Headers() 方法:append() delete() entries()...

  • fetch记录一下子

    1.原生http请求 2.fetch请求 3.上面是封装多得fetch,直接使用的fetch fetch请求对某些...

  • 聊聊fetch

    聊聊fetch fetch的使用 fetch是一个发起异步请求的新api, 在浏览器(有些不支持)中可以直接使用。...

  • 在React-Native中,使用fetch时,cookie问题

    在React-Native中,使用fetch时,cookie问题。 最近在使用fetch时,由于后端返回的请求头里...

  • Fetch的使用

    无业在家,就把一些知识总结下~~今天来总结一下fetch的使用。一些fetch的概念大家可以自己百度下。 fetc...

  • fetch的使用

    最近的工作过程中,在做js调取接口的时候,使用了fetch,原来是只知道fetch,但是没有怎么使用过。正好最近使...

  • fetch 的使用

    现在应该很少有人用原生的JS内置XMLHttpRequest对象写异步调用了,仍然用的比较多的应该是Jquery的...

  • fetch的使用

    fetch是js提供进行网络请求的框架。 调用结构是这样的。 fetch( url , options ).the...

  • Fetch的使用

    原文链接:https://www.cnblogs.com/libin-1/p/6853677.html 无论用Ja...

网友评论

      本文标题:fetch 的使用

      本文链接:https://www.haomeiwen.com/subject/rtjijxtx.html