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

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

介绍 (Introduction)

Axios is a very popular JavaScript library you can use to perform HTTP requests. It works in both Browser and Node.js platforms.

Axios是一个非常流行JavaScript库,可用于执行HTTP请求。 它可以在Browser和Node.js平台中使用。

Is supports all modern browsers, including IE8 and higher.

支持所有现代浏览器,包括IE8和更高版本。

It is promise-based, and this lets us write async/await code to perform XHR requests very easily.

它是基于Promise的,这使我们可以编写异步/等待代码来非常轻松地执行XHR请求。

Using Axios has quite a few advantages over the native Fetch API:

与本地Fetch API相比,使用Axios具有很多优势:

  • supports older browsers (Fetch needs a polyfill)支持较旧的浏览器(获取需要使用polyfill)
  • has a way to abort a request有办法中止请求
  • has a way to set a response timeout有办法设置响应超时
  • has built-in CSRF protection内置CSRF保护
  • supports upload progress支持上传进度
  • performs automatic JSON data transformation执行自动JSON数据转换
  • works in Node.js在Node.js中工作

安装 (Installation)

Axios can be installed using npm:

可以使用npm安装Axios:

npm install axios

or yarn:

或纱线 :

yarn add axios

or simply include it in your page using unpkg.com:

或使用unpkg.com将其包含在您的页面中:

<script src="https://unpkg.com/axios/dist/axios.min.js"><;/script>

Axios API (The Axios API)

You can start an HTTP request from the axios object:

您可以从axios对象启动HTTP请求:

axios({  url: 'https://dog.ceo/api/breeds/list/all',  method: 'get',  data: {    foo: 'bar'  }})

but for convenience, you will generally use

但是为了方便起见,您通常会使用

  • axios.get()

    axios.get()

  • axios.post()

    axios.post()

(like in jQuery, you would use $.get() and $.post() instead of $.ajax())

(就像在jQuery中一样,您将使用$.get()$.post()而不是$.ajax() )

Axios offers methods for all the HTTP verbs, which are less popular but still used:

Axios提供了用于所有HTTP动词的方法,这些方法不太流行但仍在使用:

  • axios.delete()

    axios.delete()

  • axios.put()

    axios.put()

  • axios.patch()

    axios.patch()

  • axios.options()

    axios.options()

It also offers a method to get the HTTP headers of a request, discarding the body.

它还提供了一种获取请求的HTTP标头,丢弃正文的方法。

GET请求 (GET requests)

One convenient way to use Axios is to use the modern (ES2017) async/await syntax.

使用Axios的一种便捷方法是使用现代(ES2017)异步/等待语法。

This Node.js example queries the Dog API to retrieve a list of all the dog breeds, using axios.get(), and it counts them:

此Node.js示例使用axios.get()查询Dog API以检索所有犬种的列表,并对其进行计数:

const axios = require('axios')const getBreeds = async () => {  try {    return await axios.get('https://dog.ceo/api/breeds/list/all')  } catch (error) {    console.error(error)  }}const countBreeds = async () => {  const breeds = await getBreeds()  if (breeds.data.message) {    console.log(`Got ${Object.entries(breeds.data.message).length} breeds`)  }}countBreeds()

If you don’t want to use async/await, you can use the Promises syntax:

如果您不想使用异步/等待,则可以使用Promises语法:

const axios = require('axios')const getBreeds = () => {  try {    return axios.get('https://dog.ceo/api/breeds/list/all')  } catch (error) {    console.error(error)  }}const countBreeds = async () => {  const breeds = getBreeds()    .then(response => {      if (response.data.message) {        console.log(          `Got ${Object.entries(response.data.message).length} breeds`        )      }    })    .catch(error => {      console.log(error)    })}countBreeds()

向GET请求添加参数 (Add parameters to GET requests)

A GET response can contain parameters in the URL, like this: https://site.com/?foo=bar.

GET响应可以在URL中包含参数,例如: https://site.com/?foo=bar : https://site.com/?foo=bar

With Axios you can perform this by simply using that URL:

使用Axios,您只需使用以下URL即可执行此操作:

axios.get('https://site.com/?foo=bar')

or you can use a params property in the options:

或者您可以在选项中使用params属性:

axios.get('https://site.com/', {  params: {    foo: 'bar'  }})

POST请求 (POST Requests)

Performing a POST request is just like doing a GET request, but instead of axios.get, you use axios.post:

执行POST请求就像做一个GET请求,但不是axios.get ,您使用axios.post

axios.post('https://site.com/')

An object containing the POST parameters is the second argument:

包含POST参数的对象是第二个参数:

axios.post('https://site.com/', { foo: 'bar' })

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

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

翻译自: https://www.freecodecamp.org/news/simple-http-requests-in-javascript-using-axios-272e1ac4a916/

使用AxiosJavaScript中的简单HTTP请求相关推荐

  1. ajax中的简单get请求,jquery 之ajax,get,post异步请求简单代码模版(示例代码)

    $.get(                        "../cart/cart_list.do", "productId="+productId, fu ...

  2. MVC架构中,用户的请求简单梳理

    MVC架构中,用户的请求分为下面3个步骤: 终端用户发送请求,路由器将请求路由到合适的Controller,Controller是逻辑实体和行为action的集合. Controller将请求映射到特 ...

  3. Python中的http网络请求,用它就对了

    软硬件环境 windows 10 64bits anaconda with python 3.7 requests 2.25.0 简介 requests是用来在Python中进行标准HTTP请求的第三 ...

  4. Gatling教程系列一简单GET请求测试(二)

    Gatling基于Scala开发的压测工具,它没有jmeter的UI配置界面,我们要想制定测试计划必须通过编写脚本,但是大家不用担心,首先脚本很简单常用的没几个,另外gatling封装的也很好我们不需 ...

  5. php循环输出多个网络地址图片,php中curl循环往请求多个URL和多线程去请求多个URL的方法...

    php 中curl 循环去请求多个URL和多线程去请求多个URL的方法 第一种:循环请求$sr=array(url_1,url_2,url_3); foreach ($sr as $k=>$v) ...

  6. JavaScript中的HTTP GET请求?

    我需要在JavaScript中执行HTTP GET请求. 最好的方法是什么? 我需要在Mac OS X破折号小部件中执行此操作. #1楼 上面有很多很棒的建议,但不是很可重用,并且经常被DOM废话和其 ...

  7. php中post提交参数_PHP中Http协议post请求参数

    这篇文章主要介绍了Http协议post请求参数的相关资料,需要的朋友可以参考下 本文给大家介绍PHP中Http协议post请求参数,具体内容如下所示: WEB开发中信息基本全是在POST与GET请求与 ...

  8. ajxs跨域 php_PHP项目中是如何处理Ajax请求与Ajax跨域的

    PHP项目中是如何处理Ajax请求与Ajax跨域的 发布时间:2020-12-14 16:35:47 来源:亿速云 阅读:98 这期内容当中小编将会给大家带来有关PHP项目中是如何处理Ajax请求与A ...

  9. java rest客户端_Java中的简单REST客户端

    java rest客户端 如今,大多数用于与某些服务器通信的移动应用程序都使用REST服务. 这些服务也是JavaScript或jQuery的常用惯例. 现在,我知道在Java中为REST服务创建客户 ...

最新文章

  1. The Swift Code之UITextField的使用,及事件委托
  2. Java开发必会的Linux命令
  3. 数据结构与算法——并查集(不相交集合)
  4. 11.2.5 属性
  5. 云小课 | 区块链关键技术之一:共识算法
  6. 70进货卖100利润是多少_服装批发利润大揭秘!让你拿货砍价心里有个底
  7. JavaScript游戏之是男人就飞10000米
  8. open cv+C++错误及经验总结(十四)
  9. mysql merge查询速度_MySQL 查询优化之 Index Merge
  10. span的title标签中的换行
  11. 回归标准差和残差平方和的关系_一文详解经典回归分析
  12. 删除修改docker网络环境
  13. 二叉树遍历算法C++实现
  14. java程序员中英文简历_2017java程序员英文简历范文
  15. 按右手定则求已经知三点的法向量
  16. eas bos根据合同类别过滤自定义核算项目
  17. 用Python做的整蛊小程序——整点阴间的东西
  18. 那个职员建议他们去计算机博物馆英语,第三单元重点句子
  19. 武林外传自动寻路CALL
  20. python爬取京东商品评价信息

热门文章

  1. 讲的真透彻!还有人不知道什么是AndroidX的吗?已拿offer入职
  2. [ BZOJ 4668 ] 冷战
  3. 深挖“窄带高清”的实现原理
  4. Sphinx编译docs文档
  5. 解决Warning: Cannot modify header information - headers already sent b...
  6. Oracle RAC
  7. 机器学习09支持向量机
  8. JAVA基础知识|lambda与stream
  9. mysql复制的工作原理及主从复制的实现
  10. 《Android 应用案例开发大全(第二版)》——导读