get请求
注意: 测试时,需要web服务器,如nginx、apache、node.js等
html页面
<script src="https://cdn.staticfile.org/axios/0.20.0/axios.min.js"></script>
<script>
axios.get('http://localhost/hello.json').then(function(res){
console.log(res);
console.log(res.data);
})
</script>
数据
hello.json 是测试数据,内容如下:
{
"msg":"hello vue"
}
测试
将html页面和json放入到nginx服务器的html文件夹下,启动服务,访问html
打印结果如下:
响应结果
- data:响应数据
- headers:响应头信息
- status:响应状态码
- statusText:响应信息
说明:res.data 是返回的数据
get请求-带参数
方式一:url传递参数
<script src="https://cdn.staticfile.org/axios/0.20.0/axios.min.js"></script>
<script>
// 为给定 ID 的 user 创建请求
axios.get('/user?id=12345')
.then(function (res) {
console.log(res);
})
.catch(function (error) {// 请求失败处理
console.log(error);
});
</script>
方式二:params选项传递参数
<script src="https://cdn.staticfile.org/axios/0.20.0/axios.min.js"></script>
<script>
axios.get('/user', {
params: {
id: 12345
}
})
.then(function (res) {
console.log(res);
})
.catch(function (error) {// 请求失败处理
console.log(error);
});
</script>
restfull 风格传参
axios.get('http://localhost:8080/user/1234').then(function(res){
console.log(res);
console.log(res.data);//服务器端返回的数据
})
箭头函数(lambda表达式)
好处: 和vue集成时,可以直接用 this 表示 vue对象
axios.get('getUserInfo', {
})
.then((res) => {
console.log(res.data);
//在 vue中可以直接用 this 表示 vue
this.leave_name=res.data.data.realName
})
.catch(function (error) {// 请求失败处理
console.log(error);
});
带上头信息
axios.get('http://localhost:8080/web_war_exploded/testJWT',{
headers: {
'auth': localStorage.getItem('auth')
}
})
.then(res => {
console.log(res);
})
.catch(error => {// 请求失败处理
console.log(error);
});
