React Native探索(五)使用fetch進(jìn)行網(wǎng)絡(luò)請(qǐng)求

前言

React Native可以使用多種方式來(lái)進(jìn)行網(wǎng)絡(luò)請(qǐng)求,比如fetch、XMLHttpRequest以及基于它們封裝的框架,fetch可以說(shuō)是替代XMLHttpRequest的產(chǎn)物,這一節(jié)我們就來(lái)學(xué)習(xí)fetch的基本用法。

1.get請(qǐng)求

fetch API是基于 Promise 設(shè)計(jì)的,因此了解Promise也是有必要的,推薦閱讀MDN Promise教程 。

get請(qǐng)求訪問(wèn)淘寶IP庫(kù)

我們先從最基礎(chǔ)的get請(qǐng)求開(kāi)始,get請(qǐng)求的地址為淘寶IP地址庫(kù),里面有訪問(wèn)接口的說(shuō)明。請(qǐng)求代碼如下所示。

 fetch('http://ip.taobao.com/service/getIpInfo.php?ip=59.108.51.32', {
             method: 'GET',
             headers: {
                'Content-Type': 'application/json'
            }
        }).then((response) => {//1
            console.log(response);
        }).catch((err) => {//2
            console.error(err);
        });

其中method用于定義請(qǐng)求的方法,這里不用寫(xiě)method也可以,fetch默認(rèn)的method就是GET。fetch方法會(huì)返回一個(gè)Promise對(duì)象,這個(gè)Promise對(duì)象中包含了響應(yīng)數(shù)據(jù)response,也就是注釋1處的response參數(shù)。在注釋1處調(diào)用then方法將response打印在控制臺(tái)Console中,then方法同樣也會(huì)返回Promise對(duì)象,Promise對(duì)象可以進(jìn)行鏈?zhǔn)秸{(diào)用,這樣就可以通過(guò)多次調(diào)用then方法對(duì)響應(yīng)數(shù)據(jù)進(jìn)行處理。在注釋2處通過(guò)catch方法來(lái)處理請(qǐng)求網(wǎng)絡(luò)錯(cuò)誤的情況。
除了上面這一種寫(xiě)法,我們還可以使用Request,如下所示。

let request = new Request('http://liuwangshu.cn', {
            method: 'GET',
            headers: ({
                    'Content-Type': 'application/json'
                 })
            });
        fetch(request).then((response) => {
            console.log(response);
        }).catch((err) => {
            console.error(err);
        });

我們先創(chuàng)建了Request對(duì)象,并對(duì)它進(jìn)行設(shè)置,最后交給fetch處理。
為了驗(yàn)證fetch的get請(qǐng)求,需要添加觸發(fā)get請(qǐng)求的代碼邏輯,如下所示。

import React, {Component} from 'react';
import {AppRegistry, View, Text, StyleSheet, TouchableHighlight} from 'react-native';
class Fetch extends Component {
    render() {
        return (
            <View style={styles.container}>
                <TouchableHighlight
                    underlayColor='rgb(210,260,260)'
                    style={{padding: 10, marginTop: 10, borderRadius: 5,}}
                    onPress={this.get}
                >
                    <Text >get請(qǐng)求</Text>
                </TouchableHighlight>
            </View>
        );
    }

    get() {
        fetch('http://ip.taobao.com/service/getIpInfo.php?ip=59.108.51.32', {
            method: 'GET',
        }).then((response) => {
            console.log(response);//1
        }).catch((err) => {//2
            console.error(err);
        });
    }
}
const styles = StyleSheet.create({
    container: {
        alignItems: 'center',
    }
});
AppRegistry.registerComponent('FetchSample', () => Fetch);

這里添加了一個(gè)TouchableHighlight,并定義了它的點(diǎn)擊事件,一旦點(diǎn)擊就會(huì)觸發(fā)get方法請(qǐng)求網(wǎng)絡(luò)。運(yùn)行程序點(diǎn)擊“get請(qǐng)求”,這時(shí)在控制臺(tái)Console中就會(huì)顯示回調(diào)的Response對(duì)象的數(shù)據(jù),它包含了響應(yīng)狀態(tài)(status)、頭部信息(headers)、請(qǐng)求的url(url)、返回的數(shù)據(jù)等信息。這次請(qǐng)求的響應(yīng)狀態(tài)status為200,返回的數(shù)據(jù)是JSON格式的,用Charles抓包來(lái)查看返回的JSON,如下圖所示。


Response對(duì)象解析

Response對(duì)象中包含了多種屬性:

  • status (number) : HTTP請(qǐng)求的響應(yīng)狀態(tài)行。
  • statusText (String) : 服務(wù)器返回的狀態(tài)報(bào)告。
  • ok (boolean) :如果返回200表示請(qǐng)求成功,則為true。
  • headers (Headers) : 返回頭部信息。
  • url (String) :請(qǐng)求的地址。

Response對(duì)象還提供了多種方法:

  • formData():返回一個(gè)帶有FormData的Promise。
  • json() :返回一個(gè)帶有JSON對(duì)象的Promise。
  • text():返回一個(gè)帶有文本的Promise。
  • clone() :復(fù)制一份response。
  • error():返回一個(gè)與網(wǎng)絡(luò)相關(guān)的錯(cuò)誤。
  • redirect():返回了一個(gè)可以重定向至某URL的response。
  • arrayBuffer():返回一個(gè)帶有ArrayBuffer的Promise。
  • blob() : 返回一個(gè)帶有Blob的Promise。

接下來(lái)對(duì)返回的Response進(jìn)行簡(jiǎn)單的數(shù)據(jù)處理,如下所示。

   get() {
        fetch('http://ip.taobao.com/service/getIpInfo.php?ip=59.108.23.12', {
            method: 'GET',
            headers: {
                'Content-Type': 'application/json'
            }
        }).then((response) => response.json())//1
            .then((jsonData) => {//2
                let country = jsonData.data.country;
                let city = jsonData.data.city;
                alert("country:" + country + "-------city:" + city);
            });
    }

訪問(wèn)淘寶IP地址庫(kù)會(huì)返回JSON數(shù)據(jù),因此在注釋1處調(diào)用response的json方法,將response轉(zhuǎn)換成一個(gè)帶有JSON對(duì)象的Promise,也就是注釋2處的jsonData。最后取出jsonData中數(shù)據(jù)并展示在Alert中,這里data是一個(gè)對(duì)象,如果它是一個(gè)對(duì)象數(shù)組我們可以這樣獲取它的數(shù)據(jù):

 let country=jsonData.data[0].country;

點(diǎn)擊“get請(qǐng)求”,效果如下所示。

2.post請(qǐng)求

post請(qǐng)求的代碼如下所示。

   post() {
        fetch('http://ip.taobao.com/service/getIpInfo.php', {
            method: 'POST',//1
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({//2
                'ip': '59.108.23.12'
            })
        }).then((response) => response.json())
            .then((jsonData) => {
                let country = jsonData.data.country;
                let city = jsonData.data.city;
                alert("country:" + country + "-------city:" + city);
            });
    }

在注釋1處將method改為POST,在注釋2處添加請(qǐng)求的body。與get請(qǐng)求類(lèi)似,這里也添加一個(gè)觸發(fā)事件來(lái)進(jìn)行post請(qǐng)求,當(dāng)點(diǎn)擊“post請(qǐng)求”時(shí),查看Charles抓包的請(qǐng)求的信息,如下圖所示。

QQ圖片20170606135823.jpg

可以看到請(qǐng)求數(shù)據(jù)是一個(gè)GSON字符串,因?yàn)樘詫欼P庫(kù)并不支持此類(lèi)型的POST請(qǐng)求,所以不會(huì)返回我們需要的地理信息數(shù)據(jù)。

3.簡(jiǎn)單封裝fetch

如果每次請(qǐng)求網(wǎng)絡(luò)都要設(shè)定method、headers、body等數(shù)據(jù),同時(shí)還要多次調(diào)用then方法對(duì)返回?cái)?shù)據(jù)進(jìn)行處理,顯然很麻煩,下面就對(duì)上面例子中的get和post請(qǐng)求做一個(gè)簡(jiǎn)單的封裝。
首先創(chuàng)建一個(gè)FetchUtils.js,代碼如下所示。

import React, {Component} from 'react';
class FetchUtils extends React.Component {
    static send(method, url, data, callback) {
        let request;
        if (method === 'get') {
            request = new Request(url, {
                method: 'GET',
                headers: ({
                    'Content-Type': 'application/json'
                })
            });
        } else if (method === 'post') {
            request = new Request(url, {
                method: 'POST',
                headers: ({
                    'Content-Type': 'application/json'
                }),
                body: JSON.stringify(data)
            });
        }
        fetch(request).then((response) => response.json())
            .then((jsonData) => {
                callback(jsonData);//1
            });
    }
}
module.exports = FetchUtils;

在FetchUtils中定義了send方法,對(duì)GET和POST請(qǐng)求做了區(qū)分處理,并在注釋1處通過(guò)callback將響應(yīng)數(shù)據(jù)response回調(diào)給調(diào)用者。
最后調(diào)用FetchUtils的send方法,分別進(jìn)行GET和POST請(qǐng)求:

    let FetchUtils=require('./FetchUtils');
    ...
    sendGet() {
        FetchUtils.send('get', 'http://ip.taobao.com/service/getIpInfo.php?ip=59.108.23.16', '', 
        jsonData => {
            let country = jsonData.data.country;
            let city = jsonData.data.city;
            alert("country:" + country + "-------city:" + city);
        })
    }
    sendPost() {
        FetchUtils.send('post', 'http://ip.taobao.com/service/getIpInfo.php', {'ip': '59.108.23.16'}, 
        jsonData => {
            let country = jsonData.data.country;
            let city = jsonData.data.city;
            alert("country:" + country + "-------city:" + city);
        })
    }

這樣我們使用Fetch訪問(wèn)網(wǎng)絡(luò)時(shí),只需要傳入需要的參數(shù),并對(duì)返回的jsonData 進(jìn)行處理就可以了。

github源碼

參考資料
Fetch API
fetch-issues-274
MDN Promise教程
ReactNative網(wǎng)絡(luò)fetch數(shù)據(jù)并展示在listview中
React Native中的網(wǎng)絡(luò)請(qǐng)求fetch和簡(jiǎn)單封裝
在 JS 中使用 fetch 更加高效地進(jìn)行網(wǎng)絡(luò)請(qǐng)求
Using Fetch


歡迎關(guān)注我的微信公眾號(hào),第一時(shí)間獲得博客更新提醒,以及更多成體系的Android相關(guān)原創(chuàng)技術(shù)干貨。
掃一掃下方二維碼或者長(zhǎng)按識(shí)別二維碼,即可關(guān)注。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容