Front and back end data interaction (V) -- what is Axios?

stupid 2021-10-14 01:33:29
end data interaction axios

One 、 What is? axios ?

axios Is based on Promise Of ajax Packaging Library , It is also the most popular front-end at present ajax Request Library . Simply put, send get、post request , It's a lightweight Library , When in use, you can directly introduce .

Two 、axios Characteristics

  1. Asynchronous ajax Request Library .
  2. On the browser side and node End can be used .
  3. Support Promise API.
  4. Support request and response interception .
  5. Automatic conversion of response data JSON data .
  6. Support request cancellation .
  7. Multiple requests can be sent in batches .
  8. The client supports security protection , Free from XSRF attack .

3、 ... and 、axios API

3.1、 install

/* npm install */
npm install axios --save
/* bower install */
bower install axios
/* Use yarn */
yarn add axios
/* cdn introduce */
<script src=""></script>

notes : If a simple static page uses , Suggest cdn Mode introduction .

3.2、axios API

towards axios Transmission related configuration parameters , Create request . Such as :axios(config)

/* If you send a post The requested configuration parameters are as follows */
method: 'post', // Request method
url: '/user/12345', // Access interface
data: { // To transmit data
firstName: 'Fred',
lastName: 'Flintstone'
/* If you send a get The requested configuration parameters are as follows */
method: 'get',
url: 'http://localhost:80/one',// Request interface
responseType: 'stream'// Response form
.then(function (response) {'save.jpg')) // Save the picture

3.3、axios Request method

above axios API Every time a request is made , You need to set its request method, response header timeout and other information , It is cumbersome to use , For convenience ,axios Aliases are provided for all supported request methods , The request can be initiated directly in a specified way , Other parameters can be set globally . Such as :


Above axios Send the request directly , When the request mode is not set , By default get request , And ajax and fetch identical . So it's a get request , You can also use get Method to send , The following example :

'1.txt' ,

It can be written in brief. axios(url,config).

Other specific methods are :

axios.get( url , config)
axios.delete( url , config)
axios.head( url , config)
axios.options( url , config) url [,data [, config ]])
axios.put( url [,data [, config ]])
axios.patch( url [,data [, config ]])

3.4、 Send requests in bulk

Multiple network requests are often executed concurrently in network requests , Sometimes we need to deal with their returned results in a unified way , therefore axios Concurrent processing .axios.all() Multiple network requests can be sent in parallel , Wait until all requests return , To continue processing .

Use the syntax :

/* The first way to deal with it */
console.log(res) // Back to res Is an array ,res[0] Is the first request data res[1] Is the second request data
/* The second way to deal with it */
res1 // Is the first request to return data
res2 // Is the second request to return data

Use axios.spread Can automatically split request return data .

1.5、 Global default configuration

The global default configuration is mainly used for each request . Save time typing code , When you want to modify , Just change one and you can change it all .

Common global default configurations are :

axios.defaults.baseURL = "http://localhost:8080/" // Configure the domain name
axios.defaults.timeout = 6000; // In milliseconds , Set timeout
/* Head set */
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN['Content-Type'] = 'application/x-www-form-urlencoded'

3.6、axios example

// Configure default parameters when instantiating
const instance = axios.create({
baseURL: ''
// Alter defaults after instance has been created
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN

Why axios Instantiation , Because global instantiation http The request has a global response interception , When some of our interfaces cannot return status codes , We will not get response, At this point, we need to be in the current api Re instantiate a axios, Set a new response intercept code .

3.7、 Interceptor

The interceptor is divided into two , There are request interception and response interception , Some businesses can be handled uniformly .

  • Request interceptor :
Request interceptor
Uniformly add... Before sending the request token
config.headers.token = sessionStorage.getItem("token") // add to toke
return config
console.log(err)// Request error
  • Response interceptors
return response
console.log(err)// Response error

3.8、 Response content

Basically in use , The first instance request succeeded , Print the results console.log(res) . The results are as follows :

// Returned from the server http Status text
// Response header information
headers: {},
//config Some configuration information at the time of request
config: {}

Four 、axios Common applications

axios It can be used on the browser side , It can also be in node.js Use in . What is sent on the browser side is XMLHttpRequest, stay node.js Send the http . image VUE、React、Node And other projects can use axios.

Link to the original text :


  1. PaddlePaddle:在 Serverless 架构上十几行代码实现 OCR 能力
  2. JavaScript数组 几个常用方法
  3. 暢談this的四種綁定方式
  4. 2021最新Vue面试必胜宝典,大厂面试题解析!
  5. Quatre façons de lier ceci
  6. Préparation au développement de l'extension tagdown
  7. Intervieweur: Parlez - moi des flotteurs CSS
  8. Packaging the View Component Library with rollup
  9. Comment un composant enfant modifie les valeurs passées par le composant parent
  10. Résumé de l'API Express
  11. Optimisation de la structure du Code if else dans le projet
  12. Fonction magique pour résoudre le problème de la fonction maybe - - fonction either
  13. 新手学前端的方法是什么 自学前端该怎么规划
  14. 云原生体系下 Serverless 弹性探索与实践
  15. 如何全方位打造安全高效的HTTPS站点(一)
  16. "Liu Jing dit che 丨 point de vue" est - ce que Custom Road est un MpV digne de la terre?
  17. 从理念到LRU算法实现,起底未来React异步开发方式
  18. Compared with Volvo XC60, Lingke 09 goes out of the spa platform. What would you choose, regardless of the brand?
  19. PaddlePaddle:在 Serverless 架构上十几行代码实现 OCR 能力
  20. 云原生体系下 Serverless 弹性探索与实践
  21. 初学者怎么学Web前端?
  22. react
  23. PaddlePaddle:在 Serverless 架构上十几行代码实现 OCR 能力
  24. JavaScript数组 几个常用方法
  25. Angular 依赖注入 - 全面解析
  26. html_day02
  27. 那些年我们前端面试中经常被问到的题!
  28. The starting price of Ducati multistada V2 in North America is less than 100000 yuan
  29. Hls.js 使用文檔
  30. Hls.js travailler avec des documents
  31. Problèmes liés à la précision JS
  32. Copie une partie des propriétés d'un objet à un autre objet
  33. Multiplexage de modules en vuex
  34. Développement multilingue Android, questions d'entrevue pour le développement de logiciels Android
  35. Chen lushai and her best friend Wang Meng play video, fearless of the pressure of public opinion, and in a good mood to dance in a bare back
  36. # Sass速通(四):继承、混合与函数
  37. Vidéo de développement de combat Android, questions d'entrevue rxjava
  38. Bugatti Chiron maintenance cost exposure! One piece for one car, burn money endlessly
  39. android应用开发基础答案,深入理解Nginx
  40. 做了三年前端,你才知道10分钟就能实现一个PC版魔方游戏
  41. Html + CSS + JS implémentation ️ Responsive Lucky Turnover ️ [with full source Sharing]
  42. Ren Jialun, who married young, was in a mess. Now she feels that it is a blessing in disguise
  43. 达梦数据库使用disql生成html格式的巡检报告
  44. React render phase parsing II - beginwork process
  45. Tableau linéaire de la structure des données (dessin à la main)
  46. In 2022, what are the highlights and popular elements in skirts to make skirts more elegant and gentle?
  47. JQuery installation
  48. Exemple de développement Android, dernière compilation de questions d'entrevue Android
  49. Differences and relations between JDK, JRE and JVM, nginx architecture diagram
  50. 【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)
  51. 【Azure 云服务】Azure Cloud Service 为 Web Role(IIS Host)增加自定义字段 (把HTTP Request Header中的User-Agent字段增加到IIS输出日志中)
  52. Questions d'entrevue pour les ingénieurs en développement Android, Android Foundation 72 questions
  53. It's kind of Cadillac CT6 to have a Mercedes Benz S-class captain and a 10At entry-level configuration, falling to less than 300000
  54. H6 meets the strong enemy again! The car body has a Cayenne visual sense, breaking 8.8 seconds, and the top configuration is less than 130000
  55. How nginx supports HTTPS and Linux kernel video tutorial
  56. Le martyr se réjouit de sa vieillesse Audi R8 V10 performance Rwd
  57. import 方式隨意互轉,感受 babel 插件的威力
  58. Le mode d'importation peut se déplacer librement pour sentir la puissance du plug - in Babel
  59. Pas de héros en termes de ventes!Du point de vue de la force du produit, la nouvelle version ax7 Mach est plus forte que H6
  60. The vue3 + TS project introduces vant as needed