api代理提取

Interested in learning JavaScript? Get my ebook at jshandbook.com

有兴趣学习JavaScript吗? 在jshandbook.com上获取我的电子书

Since IE5 was released in 1998, we’ve had the option to make asynchronous network calls in the browser using XMLHttpRequest (XHR).

自IE5于1998年发布以来,我们可以选择使用XMLHttpRequest(XHR)在浏览器中进行异步网络调用。

Quite a few years after this, Gmail and other rich apps made heavy use of it, and made the approach so popular that it had to have a name: AJAX.

在此之后的数年中,Gmail和其他丰富的应用程序大量使用了它,并使该方法如此流行,以至于必须使用一个名称: AJAX

Working directly with the XMLHttpRequest has always been a pain, and it was almost always abstracted by some library. In particular, jQuery has its own helper functions built around it:

直接使用XMLHttpRequest一直很麻烦,并且几乎总是被某些库抽象化。 特别是,jQuery围绕它构建了自己的帮助器函数:

  • jQuery.ajax()

    jQuery.ajax()

  • jQuery.get()

    jQuery.get()

  • jQuery.post()

    jQuery.post()

and so on.

等等。

They had a huge impact on making asynchronous calls more accessible. In particular, they focused on older browsers to make sure everything still worked.

它们对使异步调用更易于访问产生了巨大影响。 特别是,他们专注于较旧的浏览器,以确保所有功能仍然有效。

The Fetch API has been standardized as a modern approach to asynchronous network requests and uses Promises as a building block.

Fetch API已被标准化为异步网络请求的现代方法,并使用Promises作为构建块。

Fetch at the time of writing (Sep 2017) has a good support across the major browsers, except IE.

撰写本文时(2017年9月)的抓取在IE之外的所有主要浏览器中都有很好的支持。

The polyfill released by GitHub allows us to use fetch on any browser.

该填充工具通过GitHub的释放使我们能够利用fetch的任何浏览器。

使用提取 (Using Fetch)

Starting to use Fetch for GET requests is very simple:

开始将Fetch用于GET请求非常简单:

fetch('/file.json')

You’re already using it: fetch is going to make an HTTP request to get the file.json resource on the same domain.

您已经在使用它:fetch将发出HTTP请求以获取同一域上的file.json资源。

As you can see, the fetch function is available in the global window scope.

如您所见, fetch功能在全局window范围内可用。

Now let’s make this a bit more useful, let’s actually see what the content of the file is:

现在,让它变得更加有用,让我们实际看看文件的内容是什么:

fetch('./file.json') .then(response => response.json()).then(data => console.log(data))

Calling fetch() returns a promise. We can wait for the promise to resolve by passing a handler with the then() method of the promise.

调用fetch()返回一个promise。 我们可以通过向处理程序传递promise的then()方法来等待promise解析。

That handler receives the return value of the fetch promise, a Response object.

该处理程序接收fetch承诺的返回值,即Response对象。

We’ll see this object in more detail in the next section.

在下一节中,我们将更详细地介绍该对象。

捕捉错误 (Catching errors)

Since fetch() returns a promise, we can use the catch method of the promise to intercept any error occurring during the execution of the request, and the processing is done in the then callbacks:

由于fetch()返回一个promise,我们可以使用promise的catch方法来拦截在执行请求期间发生的任何错误, thenthen回调中完成处理:

fetch('./file.json').then(response => {  //...}.catch(err => console.error(err))

响应对象 (Response Object)

The Response Object returned by a fetch() call contains all the information about the request and the response of the network request.

fetch()调用返回的响应对象包含有关请求和网络请求响应的所有信息。

Accessing the headers property on the response object gives you the ability to look into the HTTP headers returned by the request:

访问response对象上的headers属性使您能够查看请求返回的HTTP标头:

fetch('./file.json').then(response => {  console.log(response.headers.get('Content-Type'))  console.log(response.headers.get('Date'))})

状态 (status)

This property is an integer number representing the HTTP response status.

此属性是代表HTTP响应状态的整数。

  • 101, 204, 205, or 304 is a null body status

    101204205 ,或304是一个null body状态

  • 200 to 299, inclusive, is an OK status (success)

    200299 (含)之间为OK状态(成功)

  • 301, 302, 303, 307, or 308 is a redirect

    301302303307 ,或308是一个redirect

fetch('./file.json') .then((response) => {   console.log(response.status) })

statusText (statusText)

statusText is a property representing the status message of the response. If the request is successful, the status is OK.

statusText是代表响应状态消息的属性。 如果请求成功,则状态为OK

fetch('./file.json') .then(response => console.log(response.statusText))

网址 (url)

url represents the full URL of the property that we fetched.

url代表我们获取的属性的完整URL。

fetch('./file.json') .then(response => console.log(response.url))

身体内容 (Body content)

A response has a body, accessible using the text() or json() methods, which return a promise.

响应具有一个正文,可以使用text()json()方法访问该text() ,并返回一个Promise。

fetch('./file.json').then(response => response.text()).then(body => console.log(body))
fetch('./file.json').then(response => response.json()).then(body => console.log(body))

The same can be written using the ES2017 async functions:

可以使用ES2017 异步函数编写相同的代码 :

(async () => {  const response = await fetch('./file.json')  const data = await response.json()  console.log(data)})()

请求对象 (Request Object)

The Request object represents a resource request, and it’s usually created using the new Request() API.

Request对象代表资源请求,通常使用new Request() API创建。

Example:

例:

const req = new Request('/api/todos')

The Request object offers several read-only properties to inspect the resource request details, including

Request对象提供了几个只读属性来检查资源请求的详细信息,包括

  • method: the request’s method (GET, POST, etc.)

    method :请求的方法(GET,POST等)

  • url: the URL of the request.

    url :请求的URL。

  • headers: the associated Headers object of the request

    headers :请求的关联Headers对象

  • referrer: the referrer of the request

    referrer :请求的推荐人

  • cache: the cache mode of the request (e.g., default, reload, no-cache).

    cache :请求的缓存模式(例如,默认,重新加载,无缓存)。

And exposes several methods including json(), text() and formData() to process the body of the request.

并且公开了几种方法,包括json()text()formData()来处理请求的正文。

The full API can be found here.

完整的API可以在这里找到。

Being able to set the HTTP request header is essential, and fetch gives us the ability to do this using the Headers object:

能够设置HTTP请求标头至关重要, fetch使我们能够使用Headers对象执行此操作:

const headers = new Headers()headers.append('Content-Type', 'application/json')

or, simpler:

或者,更简单:

const headers = new Headers({   'Content-Type': 'application/json' })

To attach the headers to the request, we use the Request object, and pass it to fetch() instead of simply passing the URL.

要将标头附加到请求,我们使用Request对象,然后将其传递给fetch()而不是简单地传递URL。

Instead of:

代替:

fetch('./file.json')

we do

我们的确是

const request = new Request('./file.json', {   headers: new Headers({ 'Content-Type': 'application/json' }) })
fetch(request)

The Headers object is not limited to setting values, but we can also query it:

Headers对象不仅限于设置值,我们还可以查询它:

headers.has('Content-Type') headers.get('Content-Type')

and we can delete a header that was previously set:

我们可以删除先前设置的标头:

headers.delete('X-My-Custom-Header')

POST请求 (POST Requests)

Fetch also allows you to use any other HTTP method in your request: POST, PUT, DELETE or OPTIONS.

提取还允许您在请求中使用任何其他HTTP方法:POST,PUT,DELETE或OPTIONS。

Specify the method in the method property of the request, and pass additional parameters in the header and in the request body:

在请求的method属性中指定方法,并在标头和请求正文中传递其他参数:

Example of a POST request:

POST请求的示例:

const options = {   method: 'post',   headers: {     "Content-type": "application/x-www-form-urlencoded; charset=UTF-8" },     body: 'foo=bar&test=1' }
fetch(url, options) .catch((err) => {   console.error('Request failed', err) })

如何取消获取请求 (How to cancel a fetch request)

For a few years after fetch was introduced, there was no way to abort a request once opened.

引入fetch后的几年,一旦打开请求就无法中止请求。

Now we can, thanks to the introduction of AbortController and AbortSignal, a generic API to notify abort events

现在,由于引入了AbortControllerAbortSignal (用于通知中止事件的通用API),我们可以

You integrate this API by passing a signal as a fetch parameter:

您可以通过传递信号作为访存参数来集成此API:

const controller = new AbortController()const signal = controller.signalfetch(‘./file.json’, { signal })

You can set a timeout that fires an abort event 5 seconds after the fetch request has started, to cancel it:

您可以设置一个超时,以在获取请求开始后5秒钟触发中止事件,以将其取消:

setTimeout(() => controller.abort(), 5 * 1000)

Conveniently, if the fetch already returned, calling abort() won’t cause any error.

方便的是,如果获取操作已经返回,则调用abort()不会导致任何错误。

When an abort signal occurs, fetch will reject the promise with a DOMException named AbortError:

当发生异常中止信号时,访AbortError将使用名为AbortErrorDOMException拒绝诺言:

fetch('./file.json', { signal }).then(response => response.text()).then(text => console.log(text)).catch(err => {  if (err.name === 'AbortError') {    console.error('Fetch aborted')  } else {    console.error('Another error', err)  }})

Interested in learning JavaScript? Get my ebook at jshandbook.com

有兴趣学习JavaScript吗? 在jshandbook.com上获取我的电子书

翻译自: https://www.freecodecamp.org/news/understanding-the-fetch-api-a7d4c08c2a7/

api代理提取

api代理提取_了解提取API相关推荐

  1. api如何使用_什么是API, API是如何工作的?

    什么是API? 什么是API?我们总是听说api是多么有价值,他们将对业务产生重大影响.然而,API的定义是什么? API代表应用程序编程接口.API是允许两个应用程序相互对话的软件中介.换句话说,A ...

  2. v3 微信api 请求微信_企业微信API使用基本教程

    在企业微信创建自建应用 1.登录企业微信后台,在"应用管理>自建"中点击"创建应用",填写应用信息创建. API配置表参数值获取 1.corpid:企业I ...

  3. jstree中文api文档_开发中文 API 的一些策略

    注:本文仅基于个人在其他英文编程语言中实现中文 API 的有限实践和见闻,对易语言等等中文编程语言的生态不甚了解,各种疏漏请指正. 如果要现在的我,选择一个英文 API 进行中文化,或者针对一种功能开 ...

  4. python列表字典如何提取_怎么提取字典里面的列表里面的字典的value

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 这是个股票龙虎榜的字典,怎么提取出来证券营业部? {'detail': {'symbol': 'SH600139', 'name': '西部资源', 't ...

  5. rest api 可选参数_可选类型API

    rest api 可选参数 Java 8引入了Optional类. 简而言之,不是返回null,而是检查null,而是返回Optional实例,该实例可以设置值,也可以不设置值. 这样,您不会因Nul ...

  6. api网关选型_微服务 API 网关 APISIX 发布 0.5 版本,达到可用状态

    项目介绍 APISIX (https://github.com/iresty/apisix)  是一个云原生.高性能.可扩展的微服务 API 网关. APISIX 基于 OpenResty 和 etc ...

  7. python 英文关键词提取_如何提取文章的关键词(Python版)

    项目需求: 我们采集来的文章没有关键词,在发布的时候无法设定标签,我们通过代码自动提取出文章的关键词,达到对数据加工的目的. 测试环境: Anaconda Python3.5 Win7 ultmate ...

  8. 【快代理API】获取订单IP提取余额

    接口描述 https://dps.kdlapi.com/api/getdpsvalidtime 接口地址 获取订单IP提取余额 此接口只对按量付费订单和包年包月的集中提取型订单有效 对于按量付费订单, ...

  9. api地理编码_通过地理编码API使您的数据更有意义

    api地理编码 Motivation 动机 In my second semester of my Master's degree, I was working on a dataset which ...

最新文章

  1. 大佬教你Android如何实现时间线效果
  2. android studio 编译报错:download fastutil-7.2.0.jar
  3. python app教程-Python zipapp打包教程(超级详细)
  4. 重力感应的测试程序andriod源代码
  5. 华为手机记事本导出_深夜浅谈怎样用一部手机做电影解说?
  6. 深入.NET平台和C#编程笔记 第七章 深入理解多态
  7. opencv图像分析与处理(16)- 图像压缩中的编码方法:LZW编码
  8. 【Xamarin】使用TLS 1.2保护Web请求
  9. oracle禁止访问监听,关于ORACLE数据库监听自动停止解决一例
  10. windows 安装 mongodb
  11. 天天生鲜项目 python邮箱_Django之天天生鲜项目
  12. 智慧供水:整体解决方案建设需求
  13. MySQL安装失败的原因
  14. java练习:图书销售管理系统(三),出版社管理
  15. 与华为SIP硬终端(TE40)对接注意事项
  16. 浏览器的收藏夹在哪里打开
  17. 虚拟机 邮箱服务器,虚拟机邮箱服务器设置密码
  18. 基于javaweb+mysql的电影院售票购票电影票管理系统(前台、后台)
  19. 树莓派连接GPS模块,python获取GPS数据
  20. java 日历控件_java swing 日历控件怎么实现 最好是源码

热门文章

  1. 使用screen管理后台程序
  2. jQuery的事件绑定和解绑
  3. rsync(六)命令中文手册
  4. Sass:一种CSS预处理器语言
  5. 基于opencv在摄像头ubuntu根据视频获取
  6. 一个经典实例理解继承与多态原理与优点(附源码)---面向对象继承和多态性理解得不够深刻的同学请进...
  7. HTML 页面源代码布局介绍
  8. C#定义属性-静态属性
  9. [导入]ASP.NET MVC框架开发系列课程(1):MVC模式与ASP.NET MVC框架概述.zip(8.80 MB)
  10. synchronized 底层如何实现?什么是锁升级、降级?