参考资料
Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
Demo
-
GET请求
axios.get( '/getName.do?id=1' )
.then( function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
// 请求链接参数也可以这样传输
axios.get( '/getName.do', {
params: {
id: 1
}
} )
.then( function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
- POST请求
axios.post('/getName.do', {
id: 1,
city: 'beijing'
} )
.then(function(response) {
console.log(response)
})
.catch(funciton(error) {
console.log(error)
})
- 多并发请求
function getName() {
return axios.get('/getName.do?id=1');
}
function getCity() {
return axios.get('/getCity.do?id=1');
}
axios.all([getName(), getCity()] )
.then(axios.spread( function(getNameresponse, getCityresponse) {
console.log('两个请求的响应')
}))
// 预想,并发请求可以用于带有异步校验的表单提交
常用请求配置
{
// 请求的url;url为请求必选参数,其他均为可选
url: 'getmsg.do',
// 请求方法 默认get
method: 'get',
// url请求参数,比如get请求时的请求链接里面的参数
param: {
id: 1
},
// 请求时发送数据('PUT' 'POST' 'PATCH')
data: {
id: 1,
city: 'beijing'
},
// 超时时间限制 ms,超出此时间,请求将被中断
timeout: 1000,
}
配置默认值
- 全局 axios 默认值
// 对于请求的相对路径url 会自动在url前拼接baseURL
axios.defaults.baseURL = 'https: //test.somename.com'
- 自定义实例默认值
// 创建实例
// axios.create([config]);
var demo = axios.creat({
baseURL: 'https://test.somename.com'
});
// 实例创建后可修改默认值
axios.defaults.baseURL = 'https: //test.somenameone.com'