数据请求在前端开发中的使用有两种形式
- 使用原生javascript提供的数据请求
- ajax( 四部曲,一般需要我们结合Promise去封装,使用不是很便利,但是效率很高 )
- fetch( 本身结合了Promise,并且已经做好了封装,可以直接使用 )
- 使用别人封装好的第三方库。
目前最流行的,使用率最高的是 axios。
vue中我们最常使用的
-
vue 1.x 的版本提供了一个封装库 vue-resource , 但是到了vue 2.x版本之后,这个就弃用了。
vue-resource使用方法和 axios 相似度在 95% 。
vue-resouce有jsonp方法,但是axios是没有的。 -
vue2.x版本我们最用使用的数据请求是 axios 和 fetch。
axios vs fetch
axios得到的结果会进行一层封装,而fetch会直接得到结果。
axios
1.get方法
A: 无参数
axios.get(url).then(res=>console.log(res).catch(error=>conosle.log(error))
B: 有参数
axios({
url: 'http://xxx',
method: 'get' //默认就是get,这个可以省略,
params: {
key: value
}
})
2.post
注意: axios中post请求如果你直接使用npmjs.com官网文档, 会报错
解决步骤:
1. 先设置请求头
2. 实例化 URLSearchParams的构造器函数得到params对象
3. 使用params对象身上的append方法进行数据的传参
// 统一设置请求头
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
let params = new URLSearchParams()
// params.append(key,value)
params.append('a',1)
params.append('b',2)
axios({
url: 'http://localhost/post.php',
method: 'post',
data: params,
// headers: { //单个请求设置请求头
// 'Content-Type': "application/x-www-form-urlencoded"
//}
})
.then(res => {
console.log( res )
})
.catch( error => {
if( error ){
throw error
}
})
Fetch
1.get
fetch('http://localhost/get.php?a=1&b=2')
.then(res=> res.text()) // 数据格式化 res.json() res.blob()
.then(data => {
console.log( data )
})
.catch(error => {
if( error ){
throw error
}
})
注意事项:
- A: fetch 的 get 请求的参数是直接连接在url上的, 我们可以使用Node.js提供的url或是qureystring模块来将
Object --> String - B: fetch 的请求返回的是Promise对象,所以我们可以使用.then().catch(),但是要记住.then()至少要写两个, 第一个then是用来格式化数据的,第二个then是可以拿到格式化后的数据
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>
<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/vue/2.6.10/vue.js"></script>
<style>
.row{
display: flex;
flex-direction: column;
}
button{
margin: 20px;
}
</style>
</head>
<body>
<div id="app">
<div class="container">
<div class="row">
<button type="button" class="btn btn-primary" @click = "get"> fetch-get </button>
<button type="button" class="btn btn-primary" @click = "post"> fetch-post </button>
<button type="button" class="btn btn-primary" @click = "json"> fetch-get-json数据 </button>
</div>
</div>
</div>
</body>
<script>
fetch()
new Vue({
el: '#app',
methods: {
get () {
// console.log(fetch('http://localhost/get.php?a=1&b=2')) // Promise
fetch('http://localhost/get.php?a=1&b=2') // Promise
.then( res => res.text()) //对数据进行格式化
.then( data => console.log( data ))
.catch( error => {
if( error ) throw error
})
},
post () {
fetch( 'http://localhost/post.php',{
method: 'POST',
headers: new Headers({ //解决跨域
'Content-Type': "application/x-www-form-urlencoded"
}),
body: new URLSearchParams([ // 进行参数的修改
["a",1],
["b",2]
]).toString()
})
.then( res => res.text() ) // res.json() res.blob() 不常用
.then( data => console.log( data ))
.catch( error => {
if( error ) throw error
})
},
json () {
fetch('./data/data.json')
.then( res => res.json())
.then( data => console.log( data ))
.catch( error => {
if( error ) throw error
})
}
}
})
</script>
</html>