vue 1.x 的版本提供了一個封裝庫 vue-resource , 可是到了vue 2.x版本以後,這個就棄用了
vue-resource使用方法和 axios 類似度在 95%
vue-resouce有jsonp方法,可是axios是沒有的javascript
vue2.x版本咱們最用使用的數據請求是 axios 和 fetchphp
axios獲得的結果會進行一層封裝,而fetch會直接獲得結果html
舉例:
axios前端
{data: 3, status: 200, statusText: "OK", headers: {…}, config: {…}, …} config: {adapter: ƒ, transformRequest: {…}, transformResponse: {…}, timeout: 0, xsrfCookieName: "XSRF-TOKEN", …} data: 3 headers: {content-type: "text/html; charset=UTF-8"} request: XMLHttpRequest {onreadystatechange: ƒ, readyState: 4, timeout: 0, withCredentials: false, upload: XMLHttpRequestUpload, …} status: 200 statusText: "OK" __proto__: Object
fetchvue
3
// 統一設置請求頭 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('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 ))
post() { fetch('http://localhost/erjieduan/post.php', { method: 'post', headers: new Headers({ //解決跨域 'Content-Type': "application/x-www-form-urlencoded" }), body: new URLSearchParams([ ['a', 2], ['b', 1] ]).toString() }) .then(res => res.text()) .then(data => console.log(data)) .catch(error => { if (error) throw error }) },