使用AxiosJavaScript中的简单HTTP请求

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/

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/394505.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Linux中通过命令直接删除文件中最后一行

何谓Sed(Stream EDitor):Sed原为UNIX系统上的非交谈式文字编辑器(non-interactive stream editor)。当Sed读入待编辑文件&#xff0c;会依编辑命令来进行文件的编辑工作。sed -i $d file如同其它UNIX的指令一般&#xff0c;Sed亦是由标准输入(standard input)读入欲编辑的文件&…

vb获取数组长度_如何实现数组的二分查找

二分查找是一种极其高效、简练的查找算法&#xff0c;它不仅简单&#xff0c;易用&#xff0c;而且还非常的高效。相对于顺序查找&#xff0c;二分查找在效率是呈现指数性提升&#xff0c;数据量越大&#xff0c;越能体现出二分查找法的优势。二分查找的查找过程是&#xff1a;…

400错误返回了服务器信息,使用Spring MVC,接受JSON错误的POST请求会导致返回默认的400错误代码服务器页面...

我正在使用RESTAPI。接收到带有错误JSON的POST消息(例如{sdfasdfasdf})会使Spring返回默认服务器页面&#xff0c;以显示400错误请求错误。我不想返回页面&#xff0c;我想返回自定义JSON错误对象。当使用ExceptionHandler引发异常时&#xff0c;可以执行此操作。因此&#xff…

【Python】list和tuple 区别比较

列表 List classmates [Michael, Bob, Tracy] 元组 Tuple tuple一旦初始化就不能修改&#xff0c;比如同样是列出同学的名字&#xff1a; >>> classmates (Michael, Bob, Tracy) 现在&#xff0c;classmates这个tuple不能变了&#xff0c;它也没有append()&#xff…

leetcode315. 计算右侧小于当前元素的个数(树状数组解法)

leetcode315. 计算右侧小于当前元素的个数(树状数组解法) 题目&#xff1a;给定一个整数数组 nums&#xff0c;按要求返回一个新数组 counts。数组 counts 有该性质&#xff1a; counts[i] 的值是 nums[i] 右侧小于 nums[i] 的元素的数量。 树状数组解法 java class Solution …

洛谷 P1101 单词方阵

给一nn的字母方阵&#xff0c;内可能蕴含多个“yizhong”单词。单词在方阵中是沿着同一方向连续摆放的。摆放可沿着 8个方向的任一方向&#xff0c;同一单词摆放时不再改变方向&#xff0c;单词与单词之间可以交叉,因此有可能共用字母。输出时&#xff0c;将不是单词的字母用*代…

从头学习计算机网络_如何从头开始构建三层神经网络

从头学习计算机网络by Daphne Cornelisse达芙妮康妮莉丝(Daphne Cornelisse) 如何从头开始构建三层神经网络 (How to build a three-layer neural network from scratch) In this post, I will go through the steps required for building a three layer neural network. I’…

python 文件处理

f open(chenli.txt) #打开文件 first_line f.readline() print(first line:,first_line) #读一行 print(我是分隔线.center(50,-)) data f.read() # 读取剩下的所有内容,文件大时不要用 print(data) #打印读取内容f.close() #关闭文件1…

第五章 MVC之Bundle详解

一、简述 Bundle&#xff0c;英文原意就是捆、收集、归拢。在MVC中的Bundle技术&#xff0c;也就是一个对css和js文件的捆绑压缩的技术。 它的用处&#xff1a; 将多个请求捆绑为一个请求&#xff0c;减少服务器请求数 压缩javascript&#xff0c;css等资源文件&#xff0c;减小…

所给服务器端程序改写为能够同时响应多个客户端连接请求的服务器程序_一文读懂客户端请求是如何到达服务器的...

点击上方“蓝色字体”&#xff0c;选择 “设为星标”关键讯息&#xff0c;D1时间送达&#xff01;互联网是人类历史上最伟大的发明创造之一&#xff0c;而构成互联网架构的核心在于TCP/IP协议。那么TCP/IP是如何工作的呢&#xff0c;我们先从数据包开始讲起。1、数据包一、HTTP…

消息服务器 推送技术,SSE服务器推送技术

SSE即 server send event 服务器发送事件&#xff0c;在在早期可能会使用ajax向服务器轮询的方式&#xff0c;使浏览器第一时间接受到服务器的消息&#xff0c;但这种频率不好控制&#xff0c;消耗也比较大。但是对于SSE来说&#xff0c;当客户端向服务端发送请求&#xff0c;服…

Contest2162 - 2019-3-28 高一noip基础知识点 测试5 题解版

传送门 T1 单调栈 按照b排序 在家每一个物品时&#xff0c;判断一下a和b的关系 如果s[sta[top]].a>s[i].b&#xff0c;就弹栈 记录所有时候的height&#xff0c;并取最大值 T2 单调栈裸题 单调栈是干什么的&#xff1f;&#xff1f; 单调栈是记录一个数的一侧的第一个比他大…

在package.json里面的script设置环境变量,区分开发及生产环境。注意mac与windows的设置方式不一样...

在package.json里面的script设置环境变量&#xff0c;区分开发及生产环境。 注意mac与windows的设置方式不一样。 "scripts": {"publish-mac": "export NODE_ENVprod&&webpack -p --progress --colors","publish-win": "…

leetcode 978. 最长湍流子数组(动态规划)

978. 最长湍流子数组 当 A 的子数组 A[i], A[i1], …, A[j] 满足下列条件时&#xff0c;我们称其为湍流子数组&#xff1a; 若 i < k < j&#xff0c;当 k 为奇数时&#xff0c; A[k] > A[k1]&#xff0c;且当 k 为偶数时&#xff0c;A[k] < A[k1]&#xff1b; 或 …

人工智能取代工作_人工智能正在取代人们的工作-开发人员是下一个吗?

人工智能取代工作I was recently asked to comment on whether there was any point in becoming a developer right now, because AI might be doing your job very soon.最近有人要求我评论一下现在成为开发人员是否有任何意义&#xff0c;因为AI可能很快就会完成您的工作。 …

python类self_Python类中的self到底是干啥的

Python编写类的时候&#xff0c;每个函数参数第一个参数都是self&#xff0c;一开始我不管它到底是干嘛的&#xff0c;只知道必须要写上。后来对Python渐渐熟悉了一点&#xff0c;再回头看self的概念&#xff0c;似乎有点弄明白了。首先明确的是self只有在类的方法中才会有&…

PHP中关于取模运算及符号

执行程序段<?php echo 8%(-2) ?>&#xff0c;输出结果是&#xff1a; %为取模运算&#xff0c;以上程序将输出0 $a%$b,其结果的正负取决于$a的符号。 echo ((-8)%3); //将输出-2 echo (8%(-3)); //将输出2转载于:https://www.cnblogs.com/457248499-qq-com/p…

[pytorch] Pytorch入门

Pytorch入门 简单容易上手&#xff0c;感觉比keras好理解多了&#xff0c;和mxnet很像&#xff08;似乎mxnet有点借鉴pytorch&#xff09;&#xff0c;记一记。 直接从例子开始学&#xff0c;基础知识咱已经看了很多论文了。。。 import torch import torch.nn as nn import to…

无线服务器密码让别人改了,wifi密码被改了怎么办_wifi密码被别人改了怎么办?-192路由网...

wifi密码被别人改了怎么办&#xff1f;wifi密码之所以被别人修改&#xff0c;是因为其他人知道了你路由器的登录密码。所以&#xff0c;如果发现自己wifi密码被别人修改了&#xff0c;应该立刻登录到路由器设置界面&#xff0c;修改路由器登录密码、修改wifi密码、并调整wifi加…

[archlinux][hardware] 查看SSD的使用寿命

因为最近把16GB的SSD做成了HDD的cache&#xff0c;所以比较关系寿命问题。 使用smartctl工具。 参考&#xff1a;https://www.v2ex.com/t/261373 linux 下面只有 smartmontools 这一个工具&#xff0c;而且只对像三丧和 intel 这样的大厂支持良好&#xff0c;其余的厂家文档不全…