The most complete axios guide
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('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // 也可以通过 params 对象传递参数 axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Perform POST request
axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } 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: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } });
// 发送一个 GET 请求 (GET请求是默认请求模式) axios('/user/12345');
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
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: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
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
{ // `url`是将用于请求的服务器URL url: '/user', // `method`是发出请求时使用的请求方法 method: 'get', // 默认 // `baseURL`将被添加到`url`前面,除非`url`是绝对的。 // 可以方便地为 axios 的实例设置`baseURL`,以便将相对 URL 传递给该实例的方法。 baseURL: 'https://some-domain.com/api/', // `transformRequest`允许在请求数据发送到服务器之前对其进行更改 // 这只适用于请求方法'PUT','POST'和'PATCH' // 数组中的最后一个函数必须返回一个字符串,一个 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: {'X-Requested-With': 'XMLHttpRequest'}, // `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: 'brackets'}) }, // `data`是要作为请求主体发送的数据 // 仅适用于请求方法“PUT”,“POST”和“PATCH” // 当没有设置`transformRequest`时,必须是以下类型之一: // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams // - Browser only: FormData, File, Blob // - Node only: Stream data: { firstName: 'Fred' }, // `timeout`指定请求超时之前的毫秒数。 // 如果请求的时间超过'timeout',请求将被中止。 timeout: 1000, // `withCredentials`指示是否跨站点访问控制请求 // should be made using credentials withCredentials: false, // default // `adapter'允许自定义处理请求,这使得测试更容易。 // 返回一个promise并提供一个有效的响应(参见[response docs](#response-api)) adapter: function (config) { /* ... */ }, // `auth'表示应该使用 HTTP 基本认证,并提供凭据。 // 这将设置一个`Authorization'头,覆盖任何现有的`Authorization'自定义头,使用`headers`设置。 auth: { username: 'janedoe', password: 's00pers3cret' }, // “responseType”表示服务器将响应的数据类型 // 包括 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream' responseType: 'json', // default //`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名称 xsrfCookieName: 'XSRF-TOKEN', // default // `xsrfHeaderName`是携带xsrf令牌值的http头的名称 xsrfHeaderName: 'X-XSRF-TOKEN', // 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 }), // 'proxy'定义代理服务器的主机名和端口 // `auth`表示HTTP Basic auth应该用于连接到代理,并提供credentials。 // 这将设置一个`Proxy-Authorization` header,覆盖任何使用`headers`设置的现有的`Proxy-Authorization` 自定义 headers。 proxy: { host: '127.0.0.1', port: 9000, auth: : { username: 'mikeymike', password: 'rapunz3l' } }, // “cancelToken”指定可用于取消请求的取消令牌 // (see Cancellation section below for details) cancelToken: new CancelToken(function (cancel) { }) }
axios.get('/user/12345') .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:
Global axios default value
axios.defaults.baseURL = 'https://api.example.com'; axios.defaults.headers.common['Authorization'] = AUTH_TOKEN; axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//在创建实例时设置配置默认值 var instance = axios.create({ baseURL:'https://api.example.com' }); //在实例创建后改变默认值 instance.defaults.headers.common ['Authorization'] = 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('/ longRequest',{ timeout:5000 });
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('/ user / 12345')
.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('Error',error.message);
}}
console.log(error.config);
});
Copy after loginaxios.get('/ user / 12345',{
validateStatus:function(status){
return status < 500; //仅当状态代码大于或等于500时拒绝
}}
})
Copy after login
Eliminate You can define a custom HTTP status code error range using the validateStatus configuration option.
axios.get('/ user / 12345') .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('Error',error.message); }} console.log(error.config); });
axios.get('/ user / 12345',{ validateStatus:function(status){ return status < 500; //仅当状态代码大于或等于500时拒绝 }} })
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('/user/12345', { cancelToken: source.token }).catch(function(thrown) { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } else { // 处理错误 } }); //取消请求(消息参数是可选的) source.cancel('操作被用户取消。');
var CancelToken = axios.CancelToken; var cancel; axios.get('/ user / 12345',{ 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
浏览器
在浏览器中,您可以使用URLSearchParams API,如下所示:
var params = new URLSearchParams(); params.append('param1', 'value1'); params.append('param2', 'value2'); axios.post('/foo', params);
或者,您可以使用qs库对数据进行编码:请注意,所有浏览器都不支持URLSearchParams,但是有一个polyfill可用(确保polyfill全局环境)。
var qs = require('qs'); axios.post('/foo', qs.stringify({ 'bar': 123 });
在node.js中,可以使用querystring模块,如下所示:Node.js
var querystring = require('querystring'); axios.post('http://something.com/', querystring.stringify({ foo: 'bar' });
Promise你也可以使用qs库。
axios 依赖本机要支持ES6 Promise实现。 如果您的环境不支持ES6 Promises,您可以使用polyfill。
TypeScript
axios包括TypeScript定义。
import axios from 'axios'; axios.get('/user?ID=12345');
axios在很大程度上受到Angular提供的$http服务的启发。 最终,axios努力提供一个在Angular外使用的独立的$http-like服务。
学完本文相信大家对axios更加深入了解了吧,赶紧收藏起来吧。
相关推荐:
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



How to choose the underworld relics of the Collapsed Star Dome Railway? The new five-star character Huang Quan has officially debuted, and many players have already drawn her. This character is positioned as the main C output. Below, the editor brings the Huang Quan relic set and entry recommendations, hoping to be helpful to all of you. 1. For the suit, it is recommended to choose the four-piece set [Pioneer of Backwater Diving], and for the plane jewelry, it is recommended to choose [Izumo Xianshi and Gaotian Divine Kingdom] or [Stalled Sarsotu]. 2. The main entries are selected as follows: torso critical hit rate/critical hit damage, foot attack/speed, plane ball lightning damage/attack, and link rope attack power. The selection of adverbs is: give priority to double violence, just meet the threshold or be as high as possible, and then stack speed and attack power. 3. Note: ① A four-piece outer ring set is the best for stagnant water. The thunder set is suitable for stagnant water when wearing a thunder ball and speed shoes.

How to break the password of Oppo phone if I forgot it? Unlocking strategy revealed! In daily life, mobile phones have become an indispensable part of people's lives. It is not only a communication tool, but also a platform for social entertainment. However, with the continuous upgrading of mobile phone functions, in order to protect the privacy and security of users, the setting of mobile phone lock screen passwords has become more and more important. However, it is inevitable that someone will forget their mobile phone password. How to crack the password of Oppo mobile phone when the user forgets it? This article will reveal to you how to unlock the password on your Oppo phone. first

The Collapse Star Dome Railway Tian Zhan Wu Zhan is an exclusive achievement for Huang Quan. Many players don’t know how to obtain the Tian Zhan Wu Zhan achievement. It is actually very simple. First, use Fu Xuan to attract the monsters on both sides together, and then teleport back to the previous teleport. Click and then use Huangquan to fight. Let’s take a look at this guide to obtain the Honkai Star Dome Railway Tianzhan Muzan achievement for details. Honkai Star Dome Railway Guide Complete Guide to Honkai Star Dome Railway Tianzhan Muzan Achievement Guide 1. Teleport to the location in the picture below. 2. First use Fu Xuan to attract the monsters on both sides together. 3. Then teleport back to the teleport point just now. If you have no achievement points, you can make up for them. 4. After that, you can get the achievement by using Huang Quan to cut five times in a row.

How to do double compensation on the Honkai Star Dome Railway? Double compensation is part of the main mission [Cat among Pigeons]. In this mission, you can obtain the hidden achievement of "Stealing the Blind Bet". Below, the editor will provide a detailed explanation of the double compensation mission of the Collapsed Star Dome Railway, hoping it will be helpful to the players. help. 1. Come to the new map [Chaolu Mansion] and go in through the front door. 2. After entering through the door in the picture above, rotate the four statues in the picture below correctly and the correct hidden door will appear. Then continue the task and follow the tracking task first. Go to the 1st and 2nd mission points to talk, and then switch to the 3rd position, you can consume consumables first to fill up Sand Gold's finishing move with energy before entering the battle. After entering the battle, just release Sand Gold's finishing move first. If you can get 7 [Blind Bet] points at one time, you can get the hidden achievement "Stealing the Blind Bet"; note

In the latest One Piece Hot-blooded Route mission, there is an exploration mission of Horror and Strange Graveyard Horror in One Piece. How to do Horror and Strange Graveyard Horror in One Piece and Hot-blooded Route? Many players don’t know how to play. Let’s introduce it below. Let’s take a look! One Piece: The Horror of One Piece: How to do the Cemetery Horror 1. Find the supernatural news reporters outside the ship of terror, and they guide us into the cemetery. 2. When you come to the cemetery, the plot will be triggered, and then the battle will begin. 3. After winning the battle, talk to the reporter to complete the mission.

Last season, Senju Hashirama [Kimono] demonstrated his powerful ninjutsu "Senjutsu Myojinmon", allowing everyone to see the fiery "will of fire" in his heart. The theme of this season's ninja expedition is "Poison Mist Fragrance"! The expedition order ninja Xiang Rin ["Akatsuki" robe] is a member of the Uzumaki clan. She has powerful chakra and excellent perception ability. The injured can Restore chakra and injuries by biting her skin! As the last member of the "Eagle" team to appear, this time she comes to us with two new sets of accessories, "Rock" and "Violent", let us have a look Let’s take a look at the route ideas and in-depth analysis of the Ninja World Expedition in the new season! Warm reminder: 1. This season’s Ninja World Expedition will end at 5:00 on June 13, 2024, and the expedition rankings will end on June 13, 2024.

The Nameless One is a martial arts development game. Players will play different roles, from a fledgling rookie to a famous hero. In the process of exploring the world of martial arts, we will also encounter various problems. The editor has summarized the methods and steps into this complete guide to the Unknown Man to help you solve the difficulties you encounter. The Nameless Man Strategy Collection The Nameless Man Strategy Collection Redemption Code Which Exquisite the Knight Chooses How to Upgrade the Nameless Man Redemption Code 1. Redemption Code List 1, dl6662, dl7773, dl8884, vip6665, vip7776, vip8887, dd6668, dd7779, dd88810, svip66611 , svip77712, svip88813, unknown person

The Arrival of Disaster is a side quest in the game. Many players don’t know how to complete the Arrival of Disaster. It is actually very simple. Go to Mevi Village to trigger the Arrival of Disaster quest, then talk to Ulika, and then go to Mevi Village to find it in two days. Ulika discovered that Ulika was missing. Let’s take a look at this Dragon’s Dogma 2 Disaster Arrival graphic guide for details. Dragon's Creed 2 Guide Dragon's Creed 2 Disaster Arrives Guide 1. Go to Meiwei Village and trigger the Disaster Arrive mission. 2. Talk to Ulika. 3. Go back to Meiwei Village to look for Ulika in two days and find that Ulika is missing. 4. Go to Harvard Village. 5. Complete two challenges to eliminate the lizardmen. 6. After talking to the villagers, you will find that Ulika is in the village. Then just ask Mevi to deliver the task.
