Skip to content
On this page

reco-fetch

🕒 Published at: 5 years ago

TIP

  • fetch 必然要替换 XMLHttpRequest ,所以是时候尝试 fetch 了;
  • 本封装仅针对 npm 引入;
  • 本封装依赖 es6-promisewhatwg-fetch,分别对 promisefetch 进行兼容性处理;
  • 还有一种兼容性处理是依赖 es6-promiseisomorphic-fetch ,但是看它的源码就会发现,isomorphic-fetch 只不过是引用了 whatwg-fetch ,并没有做二次开发,isomorphic-fetch 只是将 fetch 添加为全局,以便其 API 在客户端和服务器之间保持一致,所以没必要。

封装的主要内容

  1. fetch 的请求方式同 $ajaxaxios 都不太一样,并且它本身的 get 请求同其他请求对数据的处理和 herder 也不太相同,所以为了统一请求行为,方便请求过程,将请求过程进行封装;
  2. fetch 请求的结果均返回到.then()中,但是平时的习惯是是在 .then() 中处理正确结果,.catch() 中处理错误,所以对请求结果进行统一处理;
  3. fetch 本身没有 请求超时 这个概念,所以通过 Promise.race 来处理,它的作用是多个 promise 同时运行,返回的结果以最快返回结果的那个 promise 的值为准。

Fetch for browser.

Install

bash
$ npm isntall reco-fetch

Including reco-fetch

Script tag

html
<script src="/node_modules/reco-fetch/dist/recoFetch.min.js"></script>

Import

js
import recoFetch from "reco-fetch";

Config

In addition to the parameters given below, please combine other parameters MDN.

js
/**
 * @param {String, must} url    API URL
 * @param {String, must} options Parameter objects, including:
 *        method  {String, optional} Request method, default 'get'
 *        headers {Object, optional} Set request header
 *        params  {Object, optional} url parameters
 *        body    {Object, optional} request body
 *        timeout {Number, optional} Request timeout
 *        type    {String, optional} When 'post' requests, you can set: 'json', 'formData'
 */

const options = {
  method: "post",
  headers: {},
  timeout: 1000,
  body: {
    id: 1,
    value: 2,
  },
};

recoFetch(url, options)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

Example

GET

js
const options = {
  method: "get",
  params: {
    key: 1,
    value: 2,
  },
};

recoFetch(url, options)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

POST JSON

js
const options = {
  method: "post",
  body: {
    key: 1,
    value: 2,
  },
  type: "json",
};

recoFetch(url, options)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

POST formData

js
const options = {
  method: "post",
  body: {
    key: 1,
    value: 2,
  },
  type: "formData",
};

// or

const form = document.querySelector("form");
const options = {
  method: "post",
  body: form,
};

recoFetch(url, options)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

PUT

js
const options = {
  method: "put",
  body: {
    key: 1,
    value: 2,
  },
  type: "json",
};

// or

const options = {
  method: "put",
  body: JSON.stringify({
    key: 1,
    value: 2,
  }),
};

recoFetch(url, options)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

DELETE

js
const options = {
  method: "delete",
  params: {
    key: 1,
    value: 2,
  },
};

recoFetch(url, options)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

uploadFile

js
const fileField = document.querySelector("input[type='file']");

const options = {
  method: "post",
  body: {
    file: fileField.files[0],
  },
  type: "formData",
};

// or

const formData = new FormData();
const fileField = document.querySelector("input[type='file']");

formData.append("file", fileField.files[0]);

const options = {
  method: "post",
  body: formData,
};

recoFetch(url, options)
  .then((res) => {
    console.log(res);
  })
  .catch((err) => {
    console.log(err);
  });

License

MIT

如果觉得还可以,欢迎给个 Star

转自博客:午后南杂

Last updated: