您的位置:首页 > Web前端 > Vue.js

vue 之 数据请求----axios以及fetch的用法

2019-05-25 16:20 761 查看

vue之数据请求

vue2.x版本我们最常使用的数据请求是 axios 和 fetch。

数据请求的类型

get
post
head
put
delete
option
...

本文中使用的数据请求方法为get以及post方法。

相对应的数据请求接口:

  • get.php文件:
<?php
header('content-type:text/html;charset=utf-8');
header("Access-Control-Allow-Origin:*");
$a = $_GET["a"];
$b = $_GET["b"];
echo $a+$b
?>
  • post.php文件
<?php
header('content-type:text/html;charset=utf-8');
header("Access-Control-Allow-Origin:*");
$a = $_POST["a"];
$b = $_POST["b"];
echo $a+$b
?>

axios

点击进入官方api

1、什么是axios

  • 第三方库,专门用来做数据请求

2、使用方法
1、使用 npm:

$ npm install axios

2、使用cdn
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

3、axios使用

(1)axios之get方法

  • 没有参数
axios.get('url')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
  • 没有参数
//核心代码块
axios.get('url', {
params: {
key:value,
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});

(1)axios之post方法

//核心代码块
const params=new URLSearchParams()//接口定义了一些实用的方法来处理 URL 的查询字符串。
params.append('a',2)
params.append('b',3)
axios({
url:'http://localhost/post.php',
method:"POST",
data:params,
})
.then( res =>{
console.log(res)
})

关于URLSearchParams,点这里
关于axios post请求,官网的案例有一些问题,具体可以看看这篇文章

完整的代码以及运行结果

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://cdn.bootcss.com/axios/0.18.0/axios.min.js"></script>
</head>
<body>
<div id="app">
<button
type="button"
class="btn btn-primary"
@click="get_method"
>axios-get</button>
<button
type="button"
class="btn btn-primary"
@click="post_method"
>axios-post</button>
</div>
<script src="../dep/vue.js"></script>
&
1b023
lt;script>
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';//请求头设置与new URLSearchParams()作用相同,不加的话后端无法成功获取到数据,原因方面,如果想了解,请点击本段代码上方的链接。
new Vue({
el:"#app",
methods:{
//核心代码区
get_method(){
axios({
url:"http://localhost/get.php",
method:"GET",//默认为get,可以省略
params:{////params中跟着的是get请求的参数
a:1,
b:2
}
})
.then( res => {
console.log(res)
// 输出结果:{data: 3, status: 200, statusText: "OK", headers: {…}, config: {…}, …}
})
.catch( error =>{
if( error ) throw error

})
},
post_method(){
const params=new URLSearchParams()
params.append('a',2)
params.append('b',3)
axios({
url:'http://localhost/post.php',
method:"POST",
data:params,
})
.then( res =>{
console.log(res)
// 输出结果:{data: 5, status: 200, statusText: "OK", headers: {…}, config: {…}, …}

})
.catch( error =>{
if( error ) throw error
})
},

}
})

</script>

</body>
</html>

fetch

注意事项

  • fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将
    Object --> String
  • fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据

格式化处理方式有 res.json() 、res.text()、res.blob()

fetch('./data.json')
.then(res=>{
res.json() //res.text() res.blob()
})
.then( data => console.log(data))
.catch( error => console.log( error ))
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<button @click="fetch_get">fetch-get</button>
<button @click="fetch_post">fetch-post</button>
<button @click="json_get">json_get</button>
</div>

<script src="../dep/vue.js">
</script>
<script>
new Vue({
el:"#app",
methods:{
fetch_get(){
fetch("http://localhost/get.php?a=1&b=3")
.then( res => res.text() )
.then( data => console.log(data))//结果:4
},
fetch_post(){
fetch('http://localhost/post.php',{
method:"POST",
headers: new Headers({ //解决跨域
'Content-Type': "application/x-www-form-urlencoded"
}),
body:new URLSearchParams([
["a",1],
["b",6]
])
})
.then(res => res.text() )
.then(data => console.log(data))//结果:7
.catch(error => {
if( error ) throw error
})

}
})
</script>
</body>
</html>

axios和fetch最显眼的区别。就是得到的结果。axios得到的结果有一层分装,fetch没有,具体的区别可以看看这篇博客,<a href="https://segmentfault.com/a/1190000012836882”>点这里

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: