Vue數據請求 axios vs fetch

Vue數據請求

數據請求在前端開發中的使用有兩種形式

  1. 使用原生javascript提供的數據請求
  • ajax( 四部曲,通常須要咱們結合Promise去封裝,使用不是很便利,可是效率很高 )
  • fetch( 自己結合了Promise,而且已經作好了封裝,能夠直接使用 )
    • 使用格式:
  1. 使用別人封裝好的第三方庫
    目前最流行的,使用率最高的是 axios

vue中咱們最常使用的

  1. vue 1.x 的版本提供了一個封裝庫 vue-resource , 可是到了vue 2.x版本以後,這個就棄用了
    vue-resource使用方法和 axios 類似度在 95%
    vue-resouce有jsonp方法,可是axios是沒有的javascript

  2. vue2.x版本咱們最用使用的數據請求是 axios 和 fetchphp

數據請求的類型

  • get
  • post
  • head
  • put
  • delete
  • option

axios vs fetch

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總結

  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
    }
    })
  1. post
    • 注意: axios中post請求若是你直接使用npmjs.com官網文檔, 會有坑
    • 解決步驟:
      • 先設置請求頭
      • 實例化 URLSearchParams的構造器函數獲得params對象
      • 使用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 )) 
  1. post
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 }) }, 

模擬假數據

    1. mock.js
    2. json-server( 啓動一個api接口服務器 )
相關文章
相關標籤/搜索