axios與fetch實現數據請求
框架級的數據請求
1.axios(第三方庫 --- 別人封裝好的庫)
2.fetch(js原生提供)
3.vue這邊數據請求的發展
-- vue-resource(Vue 以前自己封裝使用的請求類庫),但是 vue-resource作者已經放棄更新了,不推薦再使用,但用法與axios和fetch相似。 vue-resource有jsonp數據請求類型
4.axios 和 fetch 沒有jsonp數據請求類型
--axios 和 fetch都是primose形式
1.axios 的 GET 請求
1.導入方式 cdn導入 https://www.bootcdn.cn/
<script src="https://cdn.bootcss.com/axios/0.19.0-beta.1/axios.min.js"></script>
2.當cdn導入axios時,會全局暴露一個axios對象
console.log(axios)
//控制台輸出:
ƒ (){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return e.apply(t,n)}
3.axios請求不跨域的數據時:
<div id=app>
<!-- 訪問模擬數據 -->
<button @click='getDate'>get - mock - json(自己虛擬json)</button>
</div>
<script>
new Vue({
el: '#app',
methods: {
getDate() {
//進行get請求
//axios.get() //axios.post()
//axios(options) //options 可以查看npm中axios文檔
var p = axios({
url: 'data/data.json' //模擬數據地址
})
.then(res => console.log(res)) //axios會對請求的結果進行封裝(提高安全性)
.catch(error => console.log(error))
console.log(p); // Promise {<pending>} 對象
}
}
})
</script>
4.axios請求跨域數據時候 :
4.1. 設置headers:{} 如果不設置請求頭會有跨域的報錯ACAO
4.2 發送數據的形式是params:{}
4.3 並不是所有網站都可以
get_be_data() {
//跨域請求數據 賣座電影
axios({
url: 'https://m.maizuo.com/gateway',
headers: {
'X-Client-Info': '{"a":"3000","ch":"1002","v":"5.0.4","e":"15610891489006546420515"}',
'X-Host': 'mall.film-ticket.film.list'
},
methods: 'get',
params: {
cityId: 110100,
pageNum: 1,
pageSize: 10,
type: 1,
k: 3298060
},
})
.then(res => console.log(res))
.catch(error => console.log(error))
},
5.axios請求自己后端的接口:
5.1由於同源策略的限制,會出現跨域問題
后端解決跨域: 設置請求頭 header('Access-Control-Allow-Origin:*');
前端解決:利用反向代理 ;
后端接口: (路徑:http://localhost/get.php)
<?php
//header('Access-Control-Allow-Origin:*'); //這個沒加就會有跨域問題
$a = $GET['a'];
$b = $_GET['b'];
echo $a + $b
axios發送請求:
get_myself_php_data () {
axios({
url: 'http://localhost/get.php',
params: {
a: 1,
b: 2
}
})
.then( res => console.log( res ))
.catch( error => console.log( error ))
},
以上都是axios的GET請求
2.axios 的 post 請求
1.post請求官網上有些坑 如下代碼依然存在跨域問題
axios({
url: 'http://localhost/post.php',
method: 'post',
data: {
a: 2,
b: 2
}
})
.then( res => console.log( res ))
.catch( error => console.log( error ))
解決方案:
1.先設置請求頭
2.實例化URLSeachParams的構造器函數得到params對象
3.使用params對象身上的append方法進行數據的傳參
注意:post的傳參方式params.append(key,value)
// 統一設置請求頭
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) //post請求獨特的傳參方式
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.fetch的get請求
1.fetch是原生js提供的,所以它可以做全局變量使用,它是掛載在windows對象身上的
2.特點: fetch要手動進行一次數據格式化 (axios內部已經格式化),也是promise對象(axios也是)
fetch('./data/data.json')
.then( res => res.json() ) //對數據進行格式化
.then( data => console.log( data ) ) // 這里的data就是格式化后的數據
.catch( error => console.log( error ))
3.fetch發送get請求是 參數直接寫在url上了 所以不用發送數據
4.fetch格式化有三種處理方式
4.1 .json() 格式化 json 類型數據,將json類型string(字符串)轉化成 json對象
4.2 .text() 格式化文本
4.3 .blob() 格式化二進制數據
2.fetch的post請求
參考MDN上的fetch文檔(比較權威)
https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fetch
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() )
.then( data => console.log( data ))
.catch( error => console.log( error ))
fetch 如果按照官網文檔書寫post請求,也有坑,攜帶的數據出現了問題
傳參:body: new URLSearchParams([["a", 1],["b", 2]]).toString()
請求頭設置:
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded' // 指定提交方式為表單提交
}),