Axios功能特性
● 功能特性
● 在浏览器中发送 XMLHttpRequests 请求
● 在 node.js 中发送 http请求
● 支持 Promise API
● 拦截请求和响应
● 转换请求和响应数据
● 自动转换 JSON 数据
● 客户端支持保护安全免受 XSRF 攻击
Vue中安装使用Axios
1、终端安装
npm install axios --save-dev
2、main.js文件导入Axios
import axios from 'axios'
import VueAxios from "vue-axios";
Vue.use(VueAxios,axios)
3、在组件的 methods 中使用 $ajax 命令
(1)get方式发送无参请求
methods: {
getData() { //等同于getData:function(){
this.axios({
method: 'get', //默认的请求方式是get
url: 'data/personData.json'
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
}
这是axios的回调函数,.then为请求成功的回调函数,而.catch为请求失败的回调函数。
注意:这两个回调函数都有各自独立的作用域,如果直接在里面访问 this,无法访问到 Vue 实例,只要添加一个 .bind(this) 就能解决这个问题。
then(function(res){
console.log(this.data)
}.bind(this))
简写方式
axios.get('url').then(res=>{console.log(res)}).catch(err=>{console.log(err)})
(2)get方式发送有参请求
①url传参 :url?param1¶m2&...
methods: {
getData() {
this.axios({
method: 'get',
url: 'data/personData.json?name=lhj&age=24' //url传参
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
}
简写方式
this.axios.get('url?param1¶m2').then(res=>{console.log(res)}).catch(err=>{console.log(err)})
②params传参
methods: {
getData() {
this.axios({
method: 'get',
url: 'data/personData.json',
params:{
name:"lhj",
age:20
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
}
简写方式
this.axios.get('url',{params:{name:"lhj",age:20}}).then(res=>{console.log(res)}).catch(err=>{console.log(err)})
//参数传递的是一个对象
(3)post方式发送无参请求
getData() {
this.axios({
method: 'post',
url: 'data/personData.json'
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
}
简写方式
this.axios.post('url').then(res=>{console.log(res)}).catch(err=>{console.log(err)})
(4)post方式发送含参请求 — 使用params携带参数
methods: {
getData() {
this.axios({
method: 'post',
url: 'data/personData.json',
params:{
name:"lhj",
age:20
}
})
.then(function (response) {
console.log(response)
})
.catch(function (error) {
console.log(error)
})
}
}
简写方式(post携带参数推荐该方法,数据安全)
this.axios.post('url',"name=lhj&age=20").then(res=>{console.log(res)}).catch(err=>{console.log(err)})
注意若参数是一个对象,该写法后台接收到的是null。
注意:
在get或post方式发送带参时,使用data传参后台接收到的是null,原因是此种方式的数据类型是application/json,解决办法如下:
① 用params属性进行传递,这种方式的数据类型是application/x-www-form-urlencoded;
② post的简写情况用"name=lhj"形式;
③ 服务器端接收参数使用@RequestBody 类名 对象名
或者@RequestBody Map<>map
将其封装到一个对象中。
(5)并发请求
this.axios.all([
this.axios.get('url1'),
this.axios.get('url2',{params:{}})
]).then(res=>{ //此时res是一个数组
console.log(res)
}).catch(err=>{
console.log(err)
})
或者
this.axios.all([
this.axios.get('url1'),
this.axios.get('url2',{params:{}})
]).then(
this.axios.spread((res1,res2)=>{ //多个返回数据分开
console.log(res)
console.log(res)}
}).catch(err=>{
console.log(err)
})