天天看點

Vue--前端互動 fetchAPI

1. fetch基本使用

  • fetch 就是 ajax + Promise. 使用的方式和 jquery 提供的 $.ajax() 差不多
  • fetch預設是get請求
//基本用法
		fetch('http://localhost:3000/data')
            .then(function (data) {
         	//text() 方法屬于fetchAPI的一部分,他傳回一個Promise執行個體對象,用于擷取背景傳回的資料
                return data.text();
            }).then(function (data) {
            //注意這裡才是最終資料
                console.log(data);
            })
           

2. fetch請求參數

1.常用配置選項
  • method

    (String) :HTTP請求方式,預設為get
  • body

    (String) :HTTP的請求參數
  • headers

    (Object):HTTP的請求頭,預設為{}
2.get請求參數的參數傳遞
fetch('http://localhost:3000/books/456', {
                method: 'get'
            })
            .then(function (data) {
                return data.text();
            }).then(function (data) {
                console.log(data);
            })
           
3.delete方式傳參
fetch('http://localhost:3000/books/789', {
                method: 'delete'
            })
            .then(function (data) {
                return data.text();
            }).then(function (data) {
                console.log(data);
            })
           
4.post請求方式傳參
post和put請求:
  • 需要在

    body

    中傳遞參數
  • 需要指定

    headers

fetch('http://localhost:3000/books', {
                method: 'post',
            body: 'uname=lisi&pwd=123',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
            })
            .then(function (data) {
                return data.text();
            }).then(function (data) {
                console.log(data);
            })
           
5.put請求方式傳參
fetch('http://localhost:3000/books/123', {
            method: 'put',
            body: 'uname=lisi&pwd=123',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded',
            }
        }).then(function (data) {
            return data.text();
        }).then(function (data) {
            console.log(data)
        })
           

3. fetch響應結果

響應資料格式
  • text()

    :将傳回處理成字元串類型
  • json()

    :傳回結果和

    JSON.parse(responseText)

    一樣