1、axios是什么
Axios 是一個基于 ?promise的 HTTP 庫,可以用在瀏覽器和 node.js 中。
2、axios如何安裝
(1)使用npm方式進行安裝
npm install axios
(2)使用bower方式進行安裝
bower install axios
(3)使用cdn方式進行安裝
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
3、axios使用案例
(1)get請求方式
將請求參數拼接到url中
const axios = require('axios');
?
axios.get('/user?ID=12345')
? .then(function (response) {
? ? // handle success
? ? console.log(response);
? })
? .catch(function (error) {
? ? // handle error
? ? console.log(error);
? })
? .then(function () {
? ? // always executed
? });
?
?
將請求參數放到params
axios.get('/user', {
? ? params: {
? ? ? ID: 12345
? ? }
? })
? .then(function (response) {
? ? console.log(response);
? })
? .catch(function (error) {
? ? console.log(error);
? })
? .then(function () {
? ? // always executed
? }); ?
?想要使用異步/等待?在外部函數/方法中添加'async關鍵字。?
async function getUser() {
? try {
? ? const response = await axios.get('/user?ID=12345');
? ? console.log(response);
? } catch (error) {
? ? console.error(error);
? }
}
(2)post請求方式
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) {
? ? //2個post請求現已完成
? }));
4、整合vue-axios
(1)安裝vue-axios
npm install --save axios vue-axios
(2)在main.js中加入
import Vue from 'vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
?
Vue.use(VueAxios, axios)
(3)vue-axios使用方法
這里以get請求方式舉例說明,其它請求方式類似。
Vue.axios.get(api).then((response) => {
? console.log(response.data)
})
?
this.axios.get(api).then((response) => {
? console.log(response.data)
})
?
this.$http.get(api).then((response) => {
? console.log(response.data)
})
?