使用fetch封装ajax_如何使用Fetch在JavaScript中进行AJAX调用

使用fetch封装ajax

I will be sharing bite sized learnings about JavaScript regularly in this series. We'll cover JS fundamentals, browsers, DOM, system design, domain architecture and frameworks.

在本系列中,我将定期分享有关JavaScript的小知识。 我们将介绍JS基础知识,浏览器,DOM,系统设计,域架构和框架。

Fetch is an interface for making an AJAX request in JavaScript. It is implemented widely by modern browsers and is used to call an API.

Fetch是用于在JavaScript中发出AJAX请求的接口。 它由现代浏览器广泛实现,并用于调用API。

const promise = fetch(url, [options])

Calling fetch returns a promise, with a Response object. The promise is rejected if there is a network error, and it's resolved if there is no problem connecting to the server and the server responded a status code. This status code could be 200s, 400s or 500s.

调用fetch返回带有响应对象的Promise。 如果出现网络错误,则将拒绝诺言;如果连接到服务器没有问题,并且服务器响应了状态代码,则可以解决诺言。 此状态码可以是200s,400s或500s。

A sample FETCH request -

样本FETCH请求-

fetch(url)
  .then(response => response.json())
  .catch(err => console.log(err))

The request is sent as a GET by default. To send a POST / PATCH / DELETE / PUT you can use the method property as part of options parameter. Some other possible values options can take -

默认情况下,该请求作为GET发送。 要发送POST / PATCH / DELETE / PUT,您可以将method属性用作options参数的一部分。 其他一些可能的值options可以采用-

  • method: such as GET, POST, PATCH

    method :例如GET,POST,PATCH

  • headers: Headers object

    headersheaders头对象

  • mode: such as cors, no-cors, same-origin

    mode :例如corsno-corssame-origin

  • cache: cache mode for request

    cache :请求的缓存模式

  • credentials

    credentials

  • body

    body

Check out the full list of available options here

在此处查看可用选项的完整列表

Example usage: This example demonstrates the usage of fetch to call an API and to get a list of git repositories.

用法示例:此示例演示fetch的用法,以调用API并获取git存储库列表。

const url = 'https://api.github.com/users/shrutikapoor08/repos';

fetch(url)
  .then(response => response.json())
  .then(repos => {
    const reposList = repos.map(repo => repo.name);
    console.log(reposList);
  })
.catch(err => console.log(err))

To send a POST request, here's how the method parameter can be used with async / await syntax.

要发送POST请求,以下是method参数与async / await语法一起使用的方式。

const params = {
  id: 123
}

const response = await fetch('url', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify(params)
});

const data = await response.json();


对更多JSBytes感兴趣? 订阅新闻通讯 (Interested in more JSBytes? Sign up for the newsletter)

翻译自: https://www.freecodecamp.org/news/how-to-use-fetch-api/

使用fetch封装ajax

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值