axios study notes

axios study notes
axios documentation source address: https://github.com/axios/axios
0. The description of the concept
axios on NPM is: Promise based HTTP client for the browser and node.js.
Axios is an encapsulation of ajax technology through promises, just like jQuery implements ajax encapsulation.
To put it simply: Ajax technology realizes the partial data refresh of web pages, and Axios realizes the encapsulation of Ajax.
1.Installing
$ npm install axios
2.Example
1.Performing a GET request
// Make a request for a user with a given ID
axios.get('/user?ID=12345')
.then(function (response) {
console .log(response);
})
.catch(function (error) {
console.log(error);
});
// Optionally the request above could also be done as
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

// 异步操作 Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
}
NOTE: async/await is part of ECMAScript 2017 and is not supported in Internet Explorer and older browsers, so use with caution.
2.Performing a POST request
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3.多种并发请求
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) {
// Both requests are now complete
}));
3.axios API(和ajax很像)
1.post
axios({
method: 'post',
url: '/user/12345',
data: {
firstName: 'Fred',
lastName: 'Flintstone'
}
});
2.get
axios({
method:'get',
url:'http://bit.ly/2mTM3nY',
responseType:'stream'
})
.then(function(response) {
response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});
3.默认get方法
axios('/user/12345');
4.requireJs
4.1 role
Prevent JS from blocking browser rendering
4.2 use
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.16/require.min.js"></script>

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325328728&siteId=291194637