search
HomeWeb Front-endJS TutorialThe most complete axios guide
The most complete axios guideDec 23, 2017 am 09:34 AM
axiosStrategy

axios is an HTTP client based on Promise for browsers and nodejs. This article will share with you the most complete axios strategy. With the announcement by You Yuxi, the author of vuejs, vue-resource will no longer be maintained and recommended. Everyone started using axios, and axios was understood by more and more people. I originally wanted to find a detailed guide on the Internet, but suddenly I found that the official documentation of axios itself is very detailed! Therefore, it is recommended that everyone learn this kind of library, and it is best to read its official documentation in detail. I roughly translated the official documentation of axios. I believe that as long as you understand this article thoroughly and practice it, axios will be a piece of cake! !

axios Introduction

axios is a Promise-based HTTP client for browsers and nodejs. It has the following characteristics:


  • Create XMLHttpRequest from the browser

  • Issue an http request from node.js

  • Support Promise API

  • Interception of requests and responses

  • Convert request and response data

  • Cancel request

  • Automatically convert JSON data

  • Client support to prevent CSRF/XSRF

Browser compatibility

Introduction method:

$ npm install axios
$ cnpm install axios //taobao源
$ bower install axios
或者使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>



For example:

Perform GET request

// 向具有指定ID的用户发出请求
axios.get(&#39;/user?ID=12345&#39;)
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
 
// 也可以通过 params 对象传递参数
axios.get(&#39;/user&#39;, {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

Perform POST request

axios.post(&#39;/user&#39;, {
firstName: &#39;Fred&#39;,
lastName: &#39;Flintstone&#39;
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
function getUserAccount() {
return axios.get(&#39;/user/12345&#39;);
}
 
function getUserPermissions() {
return axios.get(&#39;/user/12345/permissions&#39;);
}
 
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
//两个请求现已完成
}));

Perform multiple concurrent requests

axios API


Requests can be made by passing relevant configuration to axios.

axios(config)

// 发送一个 POST 请求
axios({
method: &#39;post&#39;,
url: &#39;/user/12345&#39;,
data: {
firstName: &#39;Fred&#39;,
lastName: &#39;Flintstone&#39;
}
});
// 发送一个 GET 请求 (GET请求是默认请求模式)
axios(&#39;/user/12345&#39;);

axios(url[, config])

Request method alias

For convenience, all Aliases are provided for supported request methods.

  • axios.request(config)

  • axios.get(url[,config])

  • axios.delete(url[,config])

  • axios.head(url[,config])

  • ##axios.post( url[,data[,config]])

  • ##axios.put(url[,data[,config]])
  • axios. patch(url[,data[,config]])
  • Note
When using the alias method, there is no need to specify the url, method and data attributes in the config.


Concurrency

Helper function handles concurrent requests.

    axios.all(iterable)
  • axios.spread(callback)
  • Create instance

You can create a new instance of axios with custom configuration.

axios.create([config])

var instance = axios.create({
baseURL: &#39;https://some-domain.com/api/&#39;,
timeout: 1000,
headers: {&#39;X-Custom-Header&#39;: &#39;foobar&#39;}
});

The available instance methods are as follows. The specified configuration will be merged with the instance configuration.

Instance methods
axios #request(config)

axios #get(url[,config])

axios #delete(url[,config])
axios #head(url[,config])
axios #post(url[,data[,config]])
axios#put(url[,data[,config]])
axios#patch( url[,data[,config]])

Request Configuration

These are the available configuration options for making requests. Only the url is required. If no method is specified, the request will default to GET.
{
// `url`是将用于请求的服务器URL
url: &#39;/user&#39;,
 
// `method`是发出请求时使用的请求方法
method: &#39;get&#39;, // 默认
 
// `baseURL`将被添加到`url`前面,除非`url`是绝对的。
// 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。
baseURL: &#39;https://some-domain.com/api/&#39;,
 
// `transformRequest`允许在请求数据发送到服务器之前对其进行更改
// 这只适用于请求方法&#39;PUT&#39;,&#39;POST&#39;和&#39;PATCH&#39;
// 数组中的最后一个函数必须返回一个字符串,一个 ArrayBuffer或一个 Stream
 
transformRequest: [function (data) {
// 做任何你想要的数据转换
 
return data;
}],
 
// `transformResponse`允许在 then / catch之前对响应数据进行更改
transformResponse: [function (data) {
// Do whatever you want to transform the data
 
return data;
}],
 
// `headers`是要发送的自定义 headers
headers: {&#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;},
 
// `params`是要与请求一起发送的URL参数
// 必须是纯对象或URLSearchParams对象
params: {
ID: 12345
},
 
// `paramsSerializer`是一个可选的函数,负责序列化`params`
// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: &#39;brackets&#39;})
},
 
// `data`是要作为请求主体发送的数据
// 仅适用于请求方法“PUT”,“POST”和“PATCH”
// 当没有设置`transformRequest`时,必须是以下类型之一:
// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
// - Browser only: FormData, File, Blob
// - Node only: Stream
data: {
firstName: &#39;Fred&#39;
},
 
// `timeout`指定请求超时之前的毫秒数。
// 如果请求的时间超过&#39;timeout&#39;,请求将被中止。
timeout: 1000,
 
// `withCredentials`指示是否跨站点访问控制请求
// should be made using credentials
withCredentials: false, // default
 
// `adapter&#39;允许自定义处理请求,这使得测试更容易。
// 返回一个promise并提供一个有效的响应(参见[response docs](#response-api))
adapter: function (config) {
/* ... */
},
 
// `auth&#39;表示应该使用 HTTP 基本认证,并提供凭据。
// 这将设置一个`Authorization&#39;头,覆盖任何现有的`Authorization&#39;自定义头,使用`headers`设置。
auth: {
username: &#39;janedoe&#39;,
password: &#39;s00pers3cret&#39;
},
 
// “responseType”表示服务器将响应的数据类型
// 包括 &#39;arraybuffer&#39;, &#39;blob&#39;, &#39;document&#39;, &#39;json&#39;, &#39;text&#39;, &#39;stream&#39;
responseType: &#39;json&#39;, // default
 
//`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称
xsrfCookieName: &#39;XSRF-TOKEN&#39;, // default
 
// `xsrfHeaderName`是携带xsrf令牌值的http头的名称
xsrfHeaderName: &#39;X-XSRF-TOKEN&#39;, // default
 
// `onUploadProgress`允许处理上传的进度事件
onUploadProgress: function (progressEvent) {
// 使用本地 progress 事件做任何你想要做的
},
 
// `onDownloadProgress`允许处理下载的进度事件
onDownloadProgress: function (progressEvent) {
// Do whatever you want with the native progress event
},
 
// `maxContentLength`定义允许的http响应内容的最大大小
maxContentLength: 2000,
 
// `validateStatus`定义是否解析或拒绝给定的promise
// HTTP响应状态码。如果`validateStatus`返回`true`(或被设置为`null` promise将被解析;否则,promise将被
  // 拒绝。
validateStatus: function (status) {
return status >= 200 && status < 300; // default
},
 
// `maxRedirects`定义在node.js中要遵循的重定向的最大数量。
// 如果设置为0,则不会遵循重定向。
maxRedirects: 5, // 默认
 
// `httpAgent`和`httpsAgent`用于定义在node.js中分别执行http和https请求时使用的自定义代理。
// 允许配置类似`keepAlive`的选项,
// 默认情况下不启用。
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
 
// &#39;proxy&#39;定义代理服务器的主机名和端口
// `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。
// 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。
proxy: {
host: &#39;127.0.0.1&#39;,
port: 9000,
auth: : {
username: &#39;mikeymike&#39;,
password: &#39;rapunz3l&#39;
}
},
 
// “cancelToken”指定可用于取消请求的取消令牌
// (see Cancellation section below for details)
cancelToken: new CancelToken(function (cancel) {
})
}
axios.get(&#39;/user/12345&#39;)
.then(function(response) {
console.log(response.data);
console.log(response.status);
console.log(response.statusText);
console.log(response.headers);
console.log(response.config);
});

Configuration Defaults When using then, you will receive a response like this:


You can specify configuration defaults that will be applied to each request.

Global axios default value

axios.defaults.baseURL = &#39;https://api.example.com&#39;;
axios.defaults.headers.common[&#39;Authorization&#39;] = AUTH_TOKEN;
axios.defaults.headers.post[&#39;Content-Type&#39;] = &#39;application/x-www-form-urlencoded&#39;;
//在创建实例时设置配置默认值
var instance = axios.create({
   baseURL:&#39;https://api.example.com&#39;
});
 
//在实例创建后改变默认值
instance.defaults.headers.common [&#39;Authorization&#39;] = AUTH_TOKEN;

Custom instance default value


Configuration priority order

Configuration will be merged with the priority order. The order is the library defaults in lib/defaults.js, then the instance's defaults attribute, and finally the request's config parameters. The latter will take precedence over the former. Here's an example.

//使用库提供的配置默认值创建实例
//此时,超时配置值为`0`,这是库的默认值
var instance = axios.create();
 
//覆盖库的超时默认值
//现在所有请求将在超时前等待2.5秒
instance.defaults.timeout = 2500;
 
//覆盖此请求的超时,因为它知道需要很长时间
instance.get(&#39;/ longRequest&#39;,{
   timeout:5000
});

Interceptor



You can intercept the request or response before it is processed by then or catch

//添加请求拦截器
axios.interceptors.request.use(function(config){
     //在发送请求之前做某事
     return config;
   },function(error){
     //请求错误时做些事
     return Promise.reject(error);
   });
 
//添加响应拦截器
axios.interceptors.response.use(function(response){
     //对响应数据做些事
     return response;
   },function(error){
     //请求错误时做些事
     return Promise.reject(error);
   });
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);

You can add the interceptor to axios Custom instance. If you may need to remove the interceptor later.

var instance = axios.create();
instance.interceptors.request.use(function () {/*...*/});

Handling Errors


axios.get(&#39;/ user / 12345&#39;)
   .catch(function(error){
     if(error.response){
       //请求已发出,但服务器使用状态代码进行响应
       //落在2xx的范围之外
       console.log(error.response.data);
       console.log(error.response.status);
       console.log(error.response.headers);
     } else {
       //在设置触发错误的请求时发生了错误
       console.log(&#39;Error&#39;,error.message);
     }}
     console.log(error.config);
   });
axios.get(&#39;/ user / 12345&#39;,{
   validateStatus:function(status){
     return status < 500; //仅当状态代码大于或等于500时拒绝
   }}
})

Eliminate You can define a custom HTTP status code error range using the validateStatus configuration option.


You can cancel the request using a cancellation token.

axios cancel token API is based on cancelable promise proposals and is currently in phase 1.

You can create a cancellation token using the CancelToken.source factory like this:
var CancelToken = axios.CancelToken;
var source = CancelToken.source();
 
axios.get(&#39;/user/12345&#39;, {
cancelToken: source.token
}).catch(function(thrown) {
if (axios.isCancel(thrown)) {
console.log(&#39;Request canceled&#39;, thrown.message);
} else {
// 处理错误
}
});
 
//取消请求(消息参数是可选的)
source.cancel(&#39;操作被用户取消。&#39;);
var CancelToken = axios.CancelToken;
var cancel;
 
axios.get(&#39;/ user / 12345&#39;,{
   cancelToken:new CancelToken(function executor(c){
     //一个执行器函数接收一个取消函数作为参数
     cancel = c;
   })
});
 
// 取消请求
clear();

NOTE: You can cancel using the same cancellation token A few requests. You can also create a cancellation token by passing the executor function to the CancelToken constructor:
Use application/x-www-form-urlencoded format

Default Below, axios serializes JavaScript objects to JSON. To send data in application/x-www-form-urlencoded format you can use one of the following options.

浏览器

在浏览器中,您可以使用URLSearchParams API,如下所示:

var params = new URLSearchParams();
params.append(&#39;param1&#39;, &#39;value1&#39;);
params.append(&#39;param2&#39;, &#39;value2&#39;);
axios.post(&#39;/foo&#39;, params);


或者,您可以使用qs库对数据进行编码:
请注意,所有浏览器都不支持URLSearchParams,但是有一个polyfill可用(确保polyfill全局环境)。

var qs = require(&#39;qs&#39;);
axios.post(&#39;/foo&#39;, qs.stringify({ &#39;bar&#39;: 123 });

在node.js中,可以使用querystring模块,如下所示:Node.js

var querystring = require(&#39;querystring&#39;);
axios.post(&#39;http://something.com/&#39;, querystring.stringify({ foo: &#39;bar&#39; });

Promise你也可以使用qs库。


axios 依赖本机要支持ES6 Promise实现。 如果您的环境不支持ES6 Promises,您可以使用polyfill。

TypeScript


axios包括TypeScript定义。

import axios from &#39;axios&#39;;
axios.get(&#39;/user?ID=12345&#39;);

axios在很大程度上受到Angular提供的$http服务的启发。 最终,axios努力提供一个在Angular外使用的独立的$http-like服务。

学完本文相信大家对axios更加深入了解了吧,赶紧收藏起来吧。

相关推荐:

vue配置axios的方法步骤示例

关于VueJs 搭建Axios接口请求工具分析

浅谈axios中的get,post方法介绍

The above is the detailed content of The most complete axios guide. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
在Vue应用中使用axios时出现“Uncaught (in promise) Error: Request failed with status code 500”怎么办?在Vue应用中使用axios时出现“Uncaught (in promise) Error: Request failed with status code 500”怎么办?Jun 24, 2023 pm 05:33 PM

在Vue应用中使用axios是十分常见的,axios是一种基于Promise的HTTP客户端,可以用于浏览器和Node.js。在开发过程中,有时会出现“Uncaught(inpromise)Error:Requestfailedwithstatuscode500”的错误提示,对于开发者来说,这个错误提示可能有些难以理解和解决。本文将会探讨这

在Vue应用中使用axios时出现“TypeError: Failed to fetch”怎么办?在Vue应用中使用axios时出现“TypeError: Failed to fetch”怎么办?Jun 24, 2023 pm 11:03 PM

最近,在使用Vue应用开发过程中,我遇到了一个常见的问题:“TypeError:Failedtofetch”错误提示。这个问题出现在使用axios进行HTTP请求时,后端服务器没有正确响应请求时发生。这种错误提示通常表明请求无法到达服务器,可能是由于网络原因或服务器未响应造成的。出现这个错误提示后,我们应该怎么办呢?以下是一些解决方法:检查网络连接由于

在Vue应用中使用axios时出现“Error: Network Error”怎么解决?在Vue应用中使用axios时出现“Error: Network Error”怎么解决?Jun 25, 2023 am 08:27 AM

在Vue应用中使用axios时出现“Error:NetworkError”怎么解决?在Vue应用的开发中,我们经常会使用到axios进行API的请求或数据的获取,但是有时我们会遇到axios请求出现“Error:NetworkError”的情况,这时我们该怎么办呢?首先,需要了解“Error:NetworkError”是什么意思,它通常表示网络连

在Vue应用中使用axios时出现“Error: timeout of xxxms exceeded”怎么办?在Vue应用中使用axios时出现“Error: timeout of xxxms exceeded”怎么办?Jun 24, 2023 pm 03:27 PM

在Vue应用中使用axios时出现“Error:timeoutofxxxmsexceeded”怎么办?随着互联网的快速发展,前端技术也在不断地更新迭代,Vue作为一种优秀的前端框架,近年来受到大家的欢迎。在Vue应用中,我们常常需要使用axios来进行网络请求,但是有时候会出现“Error:timeoutofxxxmsexceeded”的错误

Vue实现文件上传的完整指南(axios、element-ui)Vue实现文件上传的完整指南(axios、element-ui)Jun 09, 2023 pm 04:12 PM

Vue实现文件上传的完整指南(axios、element-ui)在现代Web应用程序中,文件上传已经成为一项基本的功能。无论是上传头像、图片、文档或者视频,我们都需要一个可靠的方法来将文件从用户的计算机上传到服务器中。本文将为您提供一份详细的指南,介绍如何使用Vue、axios和element-ui来实现文件上传。什么是axiosaxios是一个基于prom

Java axios与spring前后端分离传参规范是什么Java axios与spring前后端分离传参规范是什么May 03, 2023 pm 09:55 PM

一、@RequestParam注解对应的axios传参方法以下面的这段Springjava代码为例,接口使用POST协议,需要接受的参数分别是tsCode、indexCols、table。针对这个Spring的HTTP接口,axios该如何传参?有几种方法?我们来一一介绍。@PostMapping("/line")publicList

axios和SpringBoot前端怎么调用后端接口进行数据交互axios和SpringBoot前端怎么调用后端接口进行数据交互May 13, 2023 am 10:34 AM

一、介绍一个完善的系统,前后端交互是必不可少的,这个过程可以分成下面几步:前端向后端发起请求后端接口接收前端的参数后,开始层层调用方法处理数据后端将最终数据返回给前端接口前端请求成功后,将数据渲染至界面二、项目结构前端技术:axios后端技术:SpringBoot(这个也无所谓,但是你一定要有控制层的访问路径,也就是所谓的请求地址对应的方法,可以用SSM框架,SSH框架,都可以)上面是大致的文件结构,相信大家后端的数据处理都没问题,无非就是:控制层接收前端请求,调用对应的业务层接口方法业务层实现

在Vue应用中使用axios时出现“TypeError: bind is not a function”怎么办?在Vue应用中使用axios时出现“TypeError: bind is not a function”怎么办?Jun 25, 2023 am 08:31 AM

在Vue.js应用中,使用axios是非常常见的。Axios是一个强大的HTTP请求库,可以让你轻松发送异步HTTP请求。然而,在使用axios时,会遇到一些错误,其中之一就是“TypeError:bindisnotafunction”。这个错误通常是由于axios版本不兼容Vue.js的原因导致的。让我们来看一下这个错误的解决方法。首先,我们需要

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.