一、说明
Axios是一个基于Promise(ES6中用于处理异步的)的HTTP库,用于浏览器和node.js中,API。
- 浏览器中创建XMLHttpRequests
- 从node.js中创建http请求
- 支持Promise API
- 拦截请求和响应
- 转换请求数据和响应数据
- 取消请求
- 自动转换JSON数据
- 客户端支持防御XSRF
二、安装
npm安装:npm i axios;
使用cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
三、常用api说明
可使用 万能地址 发送做测试。客户端使用即在原来ajax代码替换成axios。
1、get请求axios.get(url[, config])
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios.get(’/user’, {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
axios对象调用get方法,.then()成功回调,.catch()失败回调。
get方法也可以把url中的参数提出来单独放到一个对象中。
2、post请求axios.post(url[, data[, config]])
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
3、通用请求axios(config),通过向 axios 传递相关配置config对象来创建请求
axios({
methods: 'post',
url: 'http://jsonplaceholder.typicode.com/users',
data: {
name: 'qiurx'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
})
4、执行多个并发请求
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) {
}));
axios中的all()方法,传入一个数组,数组元素即为函数调用,函数中即为请求调用。
然后,then()回调方法中调用axios自己的spread()方法。
四、创建实例
可以使用自定义配置新建一个 axios 实例axios.create([config])
var instance = axios.create({
url: 'http://jsonplaceholder.typicode.com/users',
imeout: 3000,
method: 'post'
});
instance.get('http://jsonplaceholder.typicode.com/users').then(Response=>{
console.log(Response);
});
五、所有请求配置
只有 url 是必需的。
method: ‘get’,
baseURL: ‘https://some-domain.com/api/’,
transformRequest: [function (data) {
<span class="token keyword">return</span> data<span class="token punctuation">;</span>
}],
transformResponse: [function (data) {
<span class="token keyword">return</span> data<span class="token punctuation">;</span>
}],
headers: {‘X-Requested-With’: ‘XMLHttpRequest’},
params: {
ID: 12345
},
paramsSerializer: function(params) {
return Qs.stringify(params, {arrayFormat: ‘brackets’})
},
data: {
firstName: ‘Fred’
},
timeout: 1000,
withCredentials: false,
adapter: function (config) {
},
auth: {
username: ‘janedoe’,
password: ‘s00pers3cret’
},
responseType: ‘json’,
xsrfCookieName: ‘XSRF-TOKEN’,
xsrfHeaderName: ‘X-XSRF-TOKEN’,
onUploadProgress: function (progressEvent) {
},
onDownloadProgress: function (progressEvent) {
},
maxContentLength: 2000,
validateStatus: function (status) {
return status >= 200 && status < 300;
},
maxRedirects: 5,
httpAgent: new http.Agent({ keepAlive: true }),
httpsAgent: new https.Agent({ keepAlive: true }),
proxy: {
host: ‘127.0.0.1’,
port: 9000,
auth: : {
username: ‘mikeymike’,
password: ‘rapunz3l’
}
},
cancelToken: new CancelToken(function (cancel) {
})
}
六、拦截器
在请求或响应被 then 或 catch 处理前拦截它们。
axios.interceptors.request.use(function (config) {
return config;
}, function (error) {
return Promise.reject(error);
});
即可以用在请求动画等。
七、Vue项目中使用
安装完后导入。
import axios from 'axios'
then()中的res返回包含头、状态、data数据等等,真正返回数据在此对象中的data。
使用有两种方式。
1、axios 绑定到Vue的原型上
axios并没有提供Vue.use()方法,需要绑定到Vue的原型上。
Vue.prototype.$axios = axios;
这样可以在其他组件中通过this.$axios使用axios发送请求。
export default {
methods: {
getData() {
this.$axios
.get("http://jsonplaceholder.typicode.com/users")
.then(Response => {
console.log(Response);
});
}
}
};
- 注意可能出现的问题:this的指向问题。
$axios没有定义或者get()没有定义,是因为this不是指向vue实例。可以通过var _this = this或bind(this)把this传递进去。
2、单独创建一个http.js文件,在其中配置axios,再使用export default进行导出,需要使用的位置直接使用此js模块。
所有评论(0)