Skip to content

chinanf-boy/explain-unfetch

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

4 Commits
 
 
 
 
 
 
 
 

Repository files navigation

unfetch

超小的 fetch polyfill in 500 字节.

explain

Explanation

"version": "3.0.0"

github source

english


好了,这么小,只有一个主文件

src/index.js

不如先看看例子


ponyfill vs polyfill

作为 ponyfill: 只使用unfetch

import fetch from 'unfetch';

fetch('/foo.json')
  .then( r => r.json() )
  .then( data => {
    console.log(data);
  });

全局, 作为 polyfill: 如果有原生,用原生,没有则用unfetch

import 'unfetch/polyfill';

// "fetch" 已经加载了,如果不存在的话

fetch('/foo.json')
  .then( r => r.json() )
  .then( data => {
    console.log(data);
  });

,还是不要《-🌟-》原生api,这是一个问题


例子-jsfiddle

unfetch('//jsonplaceholder.typicode.com/posts', {
	method: 'POST',
	headers: { 'Content-Type': 'application/json' },
	body: JSON.stringify({
		title: 'foo',
		body: 'bar',
		userId: 1
	})
})
	.then( r => r.json() )
	.then( data => {
		log(data);
		
		unfetch('//jsonplaceholder.typicode.com/posts/1')
			.then( r => r.json() )
			.then( log )
	});

index

export default typeof fetch=='function' ? fetch.bind()      // fetch.bind() ,使用原生
    : function(url, options) {
        
	options = options || {};
	return new Promise( (resolve, reject) => { // 增加 Promise --> async/await
		let request = new XMLHttpRequest();

		request.open(options.method || 'get', url, true);

		for (let i in options.headers) {
            // headers: { 'Content-Type': 'application/json' },
			request.setRequestHeader(i, options.headers[i]); // 设置请求-头 ---- 1
		}

		request.withCredentials = options.credentials=='include'; // ----- 2

		request.onload = () => { //        --- 3
			resolve(response()); // 获取-函数触发
		};

		request.onerror = reject; //   --- 4

        request.send(options.body);  // --- 5
    //     	body: JSON.stringify({
        // 	title: 'foo',
        // 	body: 'bar',
        // 	userId: 1
        // })

//  ---- 获取数据后,函数运行
		function response() {
            // ... 
        }
	});
}
  1. request.setRequestHeader

给指定的HTTP请求头赋值.

  1. request.withCredentials

表明在进行跨站(cross-site)的访问控制(Access-Control)请求时,是否使用认证信息(例如cookie或授权的header)。 默认为 false。

  1. request.onload

当一个资源及其依赖资源已完成加载时,将触发load事件。mdn文档

  1. request.onerror

当一个资源加载失败时会触发error事件。mdn文档

  1. request.send

发送请求. 如果该请求是异步模式(默认),该方法会立刻返回. 相反,如果请求是同步模式,则直到请求的响应完全接受以后,该方法才会返回.

有关-XMLHttpRequest-更多


response

		request.onload = () => { //        --- 3
			resolve(response()); // 获取-函数触发
		};

数据获取后,response 触发

function response() {
    let keys = [],
        all = [],
        headers = {},
        header;

    request.getAllResponseHeaders().replace(/^(.*?):\s*?([\s\S]*?)$/gm, (m, key, value) => {
        keys.push(key = key.toLowerCase()); // 所有 key
        all.push([key, value]); // 
        header = headers[key];
        headers[key] = header ? `${header},${value}` : value;
    });

    return {
        ok: (request.status/100|0) == 2,		// 200-299
        status: request.status,
        statusText: request.statusText,
        url: request.responseURL,
        clone: response,
        text: () => Promise.resolve(request.responseText),
        json: () => Promise.resolve(request.responseText).then(JSON.parse),
        blob: () => Promise.resolve(new Blob([request.response])),
        headers: {
            keys: () => keys,
            entries: () => all,
            get: n => headers[n.toLowerCase()],
            has: n => n.toLowerCase() in headers
        }
    };
}
  • getAllResponseHeaders

返回所有响应头信息(响应头名和值), 如果响应头还没接受,则返回null.

注意: For multipart requests, this returns the headers from the current part of the request, not from the original channel.


返回的对象-解释

  1. ok

: 是否成功 2==ok

  1. status

: 状态

  1. statusText

该请求的响应状态信息,包含一个状态码和原因短语 (例如 "200 OK"). 只读.

  1. url

该请求所要访问的URL

  1. clone

本函数

  1. text : function

返回异步-获取-「String类型」数据

  1. json : function

返回异步-获取-「JSON格式」数据

  1. blob : function

返回异步-获取-「Blob格式」数据

  1. headers : object

    • keys : function

    返回 [] - [key, key1,...] 请求头

    • entries : function

    返回 [] - [[key, value],[key1, value1,..] 请求头

    • get : function(n)

    返回 string headers[n] 请求头

    • has : function

    返回 Boolean,是否在请求头


About

explain: unfetch {Bare minimum fetch polyfill in 500 bytes. }🆒 微小fetch

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published