一、axios简介
axios是基于promise对Ajax的封装,是异步请求的一种解决方案。那么对于异步请求已经有原生ajax和jQuery的ajax是jQuery的,是针对以前的mvc架构的一套解决方案,现在的前端出来一个mvvm架构,这时候的$ajax使用起来就不是那么友好了,而且原生的Ajax,用起来又十分的麻烦,所以axios就应运而生了,并被大多数人所认可。
二、axios的使用方式
- 下载源文件,script_src方式使用。
- cdn引入使用。
- npm加载使用。
三、axios的基本使用
- 默认无参请求方式
//使用默认方式发送请求 => get方式
axios({
url: 'http://localhost:9999/student/student/getAllstudent',
}).then( res => {
console.log('res');
})
- 指定请求为get无参方式
axios({
url: 'http://localhost:9999/student/student/getAllstudent',
//method属性指定请求的方式
method: 'get'
}).then(res => {
console.log(res)+
})
- 使用post方式发送无参请求
axios({
url: '请求地址',
method: 'post' //指定为post请求方式
}).then( res => {
console.log(res);
})
//then方法相当于promise中的then方法,接受两个参数:
//第一个参数是: resolve的callback函数
//第二个函数是: reject的callback函数
- 使用get方式发送有参请求1
axios({
url: '请求地址?id=1',//?后面可以携带参数
//不指定method默认是get请求方式
}).then( res => {
console.log(res);//请求成功的回调函数
})
- 使用get方式发送有参请求2 -- 在axios中配置属性
axios({
url: '请求地址',
method: 'get',
params: {
id: '1',
name: '张三'
}
//axios中使用有参请求时,是在属性params属性中配置的,属性值是一个对象
//里卖弄配置相应的对象
}).then( res => {
console.log(res);
})
- 使用post方式发送有参请求
axios({
url: 'post请求地址',
method: 'post', //请求方式
//params参数配置
params: {
id: '1',
name: '魂魂张'
}
}).then( res => {
console.log(res)
})
四、axios请求方式(简写)
- 使用axios.get()方式发送无参请求
axios.get('url请求地址').then( res => {
console.log(res);
}).catch( err => {
console.log(err);
})
//catch()函数相当于promise中的catch函数针对于处理请求发生错误的形式
- 使用axios.get()方式发送有参请求
axios.get('url请求地址',{params: {
id: 1,
name: '魂魂张'
}}).then( res => {
console.log(res);
}).catch( err => {
console.log(err);
})
- axios.post()方式发送无参请求
axios.post('url').then( res => {
console.log(res);
}).catch( err => {
console.log(err)
})
- axios.post()方式发送有参请求
axios.post('url',"name:魂魂张&id=10").then( res => {
console.log(res);
}).catch( err => {
console.log(err)
})
//使用axios.post()这种方式进行有参的post请求的时候
//需要将参数写在引号中,作为字符串去传递,多个参数使用&
//符号进行连接
使用axios.post()这种方式进行有参的post请求的时候需要将参数写在引号中,作为字符串去传递,多个参数使用&符号进行连接