Installing
Using npm:
$ npm install axios |
Using bower:
$ bower install axios |
Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script> |
axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])
get请求
const axios = require('axios');
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }) .then(function () { // always executed });
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) { // Both requests are now complete })); |
可以通过将相关配置传递到来发出请求axios
。
axios的全局配置
http.js中对axios进行了一些默认配置:
import Vue from 'vue'
import axios from 'axios'
import config from './config'
// config中定义的基础路径是:http://api.leyou.com/api
axios.defaults.baseURL = config.api; // 设置axios的基础请求路径
axios.defaults.timeout = 2000; // 设置axios的请求时间
Vue.prototype.$http = axios;// 将axios赋值给Vue原型的$http属性,这样所有vue实例都可使用该对象
http.js中导入了config的配置:
- http.js对axios进行了全局配置:
baseURL=config.api
,即http://api.leyou.com/api
。因此以后所有用axios发起的请求,都会以这个地址作为前缀。 - 通过
Vue.property.$http = axios
,将axios
赋值给了 Vue原型中的$http
。这样以后所有的Vue实例都可以访问到$http,也就是访问到了axios了。
methods: { getDataFromServer() { // 从服务的加载数的方法。 // 发起请求 this.$http.get("/item/brand/page", { params: { key: this.search, // 搜索条件 page: this.pagination.page,// 当前页 rows: this.pagination.rowsPerPage,// 每页大小 sortBy: this.pagination.sortBy,// 排序字段 desc: this.pagination.descending// 是否降序 } }).then(resp => { // 这里使用箭头函数 this.brands = resp.data.items; this.totalBrands = resp.data.total; // 完成赋值后,把加载状态赋值为false this.loading = false; }) }}