axios
axios
axios对原生ajax进行了封装,简化书写,快速开发,用于发送异步请求。
查看 axios
docs
定义
Axios 是一个基于 promise
网络请求库,作用于node.js
和浏览器中。 它是 isomorphic
的(即同一套代码可以运行在浏览器和node.js中)。在服务端它使用原生 node.js
http
模块, 而在客户端 (浏览端) 则使用 XMLHttpRequests。
用例
发起一个 GET
请求
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| const axios = require('axios');
axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { });
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .finally(function () { });
async function getUser() { try { const response = await axios.get('/user?ID=12345'); console.log(response); } catch (error) { console.error(error); } }
|
注意: 由于async/await
是ECMAScript
2017中的一部分,而且在IE和一些旧的浏览器中不支持,所以使用时务必要小心。
发起一个 POST
请求
1 2 3 4 5 6 7 8 9 10
| axios.post('/user', { firstName: 'Fred', lastName: 'Flintstone' }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
|