Skip to content

fetch从api到最佳实践 #8

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Open
1 task done
phoebeCodeSpace opened this issue Jul 5, 2017 · 0 comments
Open
1 task done

fetch从api到最佳实践 #8

phoebeCodeSpace opened this issue Jul 5, 2017 · 0 comments
Labels

Comments

@phoebeCodeSpace
Copy link
Owner

fetch

JavaScript 通过XMLHttpRequest(XHR)来执行异步请求,它在设计上不符合职责分离原则,将输入、输出和用事件来跟踪的状态混杂在一个对象里。fetch的出现正是为了解决上面提到的那些缺陷。

兼容性

fetch是相对较新的技术,在使用fetch来进行项目开发时,先了解fetch在浏览器兼容性的问题。

fetch基于Promise来实现,在低版本浏览器中Promise可能也未被原生支持,所以除了fetch本身的polyfill,还需要Promise的polyfill:

polyfill

Fetch API

Fetch引入了3个接口,它们分别是 Headers,Request 以及 Response 。

Headers

Headers接口是一个简单的多映射的名-值表,允许您对HTTP请求和响应头执行各种操作。

Request

Request接口定义了通过HTTP请求资源的request格式。

  • Request.method 请求使用的方法 (GET, POST, 等)
  • Request.url 请求使用的 URL
  • Request.mode 请求的模式 (例如: cors, no-cors, same-origin)
  • Request.cache 请求的缓存模式 (例如: default, reload, no-cache)
  • Request.credentials 发送cookies (例如: omit, same-origin, include)

Response

通常在fetch()的回调中获得。

Fetch用法

基本用法

请求一个URL,获取JSON格式的返回结果。

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

最佳实践

最佳实践为工作总结,根据工作中的应用不断更新。

  • POST请求,请求资源格式为base64编码。

base64url

  //javascript
  import base64url from 'base64url';

  const url = '';           //请求url
  const requset={};         //请求数据

  fetch(url,
      { method: "POST",                    //请求方法:POST
        mode:"cors",                       //请求模式:支持跨域请求
        cache: 'reload',                   //请求cache模式:reload
        body :JSON.stringify(requset)      //请求的 body 信息
      }).then(response =>  { return response.text()})
    .then(response => console.log(JSON.parse(base64url.decode(response))))
    .catch(e => console.log("Oops, error", e))

参考文档

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant