AJAX 的封装
https://www.axios-http.cn/docs/intro
// 发起一个post请求axios({method: 'post',url: '/user/12345',data: {firstName: 'Fred',lastName: 'Flintstone'}});
// 在 node.js 用GET请求获取远程图片axios({method: 'get',url: 'http://bit.ly/2mTM3nY',responseType: 'stream'}).then(function (response) {response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))});
快速入门
// 向给定ID的用户发起请求 axios.get(‘/user?ID=12345’) .then(function (response) { // 处理成功情况 console.log(response); }) .catch(function (error) { // 处理错误情况 console.log(error); }) .then(function () { // 总是会执行 });
// 上述请求也可以按以下方式完成(可选) axios.get(‘/user’, { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // 总是会执行 });
// 支持async/await用法 async function getUser() { try { const response = await axios.get(‘/user?ID=12345’); console.log(response); } catch (error) { console.error(error); } }
<a name="LOcGu"></a>## POST 方法实践```javascriptaxios.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');}Promise.all([getUserAccount(), getUserPermissions()]).then(function (results) {const acct = results[0];const perm = results[1];});
