如何使用Fetch API

作者: 码农氵 | 来源:发表于2017-03-17 16:26 被阅读1778次
alt textalt text

传统的Request

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onreadystatechange = function() {
  if (this.readyState === 4) {
    if (this.status >= 200 && this.status < 400) {
      // Success!
      var resp = this.responseText;
    } else {
      // Error :(
    }
  }
};

request.send();
request = null;

jQuery ajax

$.ajax({
  type: 'GET',
  url: '/my/url',
  success: function(resp) {

  },
  error: function() {

  }
});

传统的XMLHttpRequest请求闲的非常的杂乱,而优雅的ajax又不得不额外加载jQuery这个80K左右的框架

但是现在,我们可以使用Fetch,提供了对 Request 和 Response (以及其他与网络请求有关的)对象的通用定义,它还提供了一种定义,将 CORS 和 HTTP 原生的头信息结合起来,取代了原来那种分离的定义。

But,Fetch 兼容性,可以看到,兼容性很差,移动端全军覆没,不过可以使用Fetch polyfill

alt textalt text

使用方法

fetch(url) // Call the fetch function passing the url of the API as a parameter
.then(function() {
    // Your code for handling the data you get from the API
})
.catch(function() {
    // This is where you run code if the server returns any errors
});

so easy

现在使用Fetch创建一个简单的Get请求,将从Random User API获取的数据展示在网页上

<h1>Authors</h1>
<ul id="authors"></ul>
const ul=document.getElementById('authors');
const url="https://randomuser.me/api/?results=10";

fetch(url)
.then(function(data){
})
.catch(function(err){
});

首先获取authors,定义常量URL,然后调用Fetch API并且使用上面定义的常量URL
,但是此处获取的并不是JSON,而是需要进行转换,这些方法包括:

  • clone()
  • redirect()
  • arrayBuffer()
  • formData()
  • blob()
  • text()
  • json()

此处我们需要返回的是json对象,所以上面的js应该:

fetch(url)
.then((resp) => resp.json()) //转换成json对象
.then(function(data) {
    dom操作
  })
})

接下来定义两个函数:

function createNode(el){
  return document.createElement(el);
}

function append(parent,el){
  retrun parent.appendChild(el);
}

编写请求成功后操作

fetch(url)
.then((resp)=>resp.json())
.then(function(data){
  let authors=data.results;
  return authors.map(function(author){
    let li=createNode('li'),
        img=createNode('img'),
        span=createNode('span');
    img.src=author.picture.medium;
    span.innerHTML=`${author.name.first} ${author.name.last}`;
    append(li,img);
    append(li,span);
    append(ul,li);
  })
})
.catch(function(err){
  console.log(err)
})

处理更多请求(POST)

Fetch默认是GET方式,此外还可以使用自定义头部与请求方式,如:

const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
    name: 'Sara'
}
// The parameters we are gonna pass to the fetch function
let fetchData = { 
    method: 'POST', 
    body: data,
    headers: new Headers()
}
fetch(url, fetchData)
.then(function() {
    // Handle response you get from the server
});

还可以使用request构建请求对象,如:

const url = 'https://randomuser.me/api';
// The data we are going to send in our request
let data = {
    name: 'Sara'
}
// Create our request constructor with all the parameters we need
var request = new Request(url, {
    method: 'POST', 
    body: data, 
    headers: new Headers()
});

fetch(request)
.then(function() {
    // Handle response we get from the API
})

相关文章

  • Fetch

    Fetch API使用 Fetch

  • 如何使用Fetch API

    传统的Request jQuery ajax 传统的XMLHttpRequest请求闲的非常的杂乱,而优雅的aja...

  • ES6 Fetch API HTTP请求实用指南

    本次将介绍如何使用Fetch API(ES6 +)对REST API的 HTTP请求,还有一些示例提供给大家便于大...

  • 详解ES6 Fetch API HTTP请求实用指南

    本次将介绍如何使用Fetch API(ES6 +)对REST API的 HTTP请求,还有一些示例提供给大家便于大...

  • 聊聊fetch

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

  • JS异步处理系列二 XHR Fetch

    参考AJAX 之 XHR, jQuery, Fetch 的对比使用更优雅的异步请求API——fetch 一、原生 ...

  • react数据请求

    fetch API fetch是基于Promise设计,所以不支持Promise的浏览器建议使用cross_fet...

  • 前端 | 一些实用的npm库

    dependencies 1. whatwg-fetch 有些浏览器不支持fetch API,可以使用这个poly...

  • XMLHttpRequest总结

    原文链接:你真的会使用XMLHttpRequest吗?这个API很“迷人”——(新的Fetch API)Servi...

  • fetch

    fetch api

网友评论

    本文标题:如何使用Fetch API

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