1. 程式人生 > >ES6中Fetch的封裝及使用,炒雞簡單~

ES6中Fetch的封裝及使用,炒雞簡單~

之前寫過一篇《ajax、axios、fetch之間的詳細區別以及優缺點》 戳這裡

1.封裝 (http.js)

class Ajax {
  get(url) {
    return new Promise((resolve, reject) => {
      fetch(url)
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err))

    })
  }

  // post方式
  post(url, data) {
    return new Promise((resolve, reject) => {
      fetch(url, {
          method: 'POST',
          headers: {
            'Content-type': 'application/json'
          },
          body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err))

    })
  }


  //put 修改
  put(url, data) {
    return new Promise((resolve, reject) => {
      fetch(url, {
          method: 'PUT',
          headers: {
            'Content-type': 'application/json'
          },
          body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err))

    })
  }

  //delete
  delete(url, data) {
    return new Promise((resolve, reject) => {
      fetch(url, {
          method: 'DELETE',
          headers: {
            'Content-type': 'application/json'
          },
          body: JSON.stringify(data)
        })
        .then(res => res.json())
        .then(data => resolve('資料刪除成功!'))
        .catch(err => reject(err))
    })
  }
}
export default new Ajax();//ES6匯出

2.呼叫

import http from "./http.js"//引入方式 這裡用的是ES6的方法,需要babel配合webpack打包
//普通引入使用src引入之後  const http = new Ajax();   即可
// get請求資料
http.get('http://jsonplaceholder.typicode.com/users')
  .then((data) => {
    console.log(data)
  })
  .catch(err => console.log(err))

// post傳輸資料
const data = {
  name: 'candy',
  username: 'candy',
  email: '
[email protected]
' }; //post user http.post('http://jsonplaceholder.typicode.com/users', data) .then(data => console.log(data)) .catch(err => console.log(err)) // update user ,修改後會發現修改後ID為2的資料會變成上頁面定義的data http.put('http://jsonplaceholder.typicode.com/users/2', data) .then(data => console.log(data)) .catch(err => console.log(err)) //delete user 刪除下標為2裡的資料 http.delete('http://jsonplaceholder.typicode.com/users/2', data) .then(data => console.log(data)) .catch(err => console.log(err))

貼個徵婚啟事~~~

受朋友之託。
女,程式設計師,22歲,未婚,身高167cm,體重48KG,山東青島。
目前在阿里巴巴工作,負責支付寶相關業務,工號  7212127  支付寶搜尋工號可見照片和個人資訊呢。
漂亮大方,愛好讀書、健身、游泳、吃雞。
青島有房一套,有車。
父母退休,家庭不拜金、人務實,一直沒有合適的男朋友。
她本人要求不高,只要對她真心好就行。