在react-native開發中,使用Fetch進行網絡請求。官方文檔上的網絡請求html
1 fetch(@"http://www.baidu.com") 2 .then((response) => response.json()) 3 .then((responseJson) => { 4 console.log(responseJson);//打印返回的數據 5 }); 6 }) 7 .catch((error)=>{ 8 console.log(error);//打印報的錯 9 })
catch住fetch可能拋出的異常,不然出錯時你可能看不到任何提示。react
Fetch還有可選的第二個參數,能夠用來定製HTTP請求一些參數。你能夠指定header參數,或是指定使用POST方法,又或是提交數據等等:web
1 fetch('https://mywebsite.com/endpoint/', { 2 method: 'POST', 3 headers: { 4 'Accept': 'application/json', 5 'Content-Type': 'application/json', 6 }, 7 body: JSON.stringify({ 8 firstParam: 'yourValue', 9 secondParam: 'yourOtherValue', 10 }) 11 })
若是你的服務器沒法識別上面POST的數據格式,那麼能夠嘗試傳統的form格式:json
1 fetch('https://mywebsite.com/endpoint/', { 2 method: 'POST', 3 headers: { 4 'Content-Type': 'application/x-www-form-urlencoded', 5 }, 6 body: 'key1=value1&key2=value2' 7 })
能夠參考Fetch請求文檔來查看全部可用的參數。react-native
1 /* 2 * get請求 3 * url:請求地址 4 * params:參數 5 * callback:回調函數 6 * */ 7 static get(url,params,callback){ 8 if (params) { 9 let paramsArray = []; 10 //拼接參數 11 Object.keys(params).forEach(key => paramsArray.push(key + '=' + params[key])) 12 if (url.search(/\?/) === -1) { 13 url += '?' + paramsArray.join('&') 14 } else { 15 url += '&' + paramsArray.join('&') 16 } 17 } 18 //fetch請求 19 fetch(url,{ 20 method: 'GET', 21 }) 22 .then((response) => { 23 callback(response) 24 }) 25 .catch((error) => { 26 alert(error) 27 }); 28 }
post有兩種形式:服務器
1 /* 2 * post請求 3 * url:請求地址 4 * params:參數,這裏的參數格式是:{param1: 'value1',param2: 'value2'} 5 * callback:回調函數 6 * */ 7 static postJSON(url,params,callback){ 8 //fetch請求 9 fetch(url,{ 10 method: 'POST', 11 headers: { 12 'Accept': 'application/json', 13 'Content-Type': 'application/json', 14 }, 15 body:JSON.stringify(params) 16 }) 17 .then((response) => response.json()) 18 .then((responseJSON) => { 19 callback(responseJSON) 20 }) 21 .catch((error) => { 22 console.log("error = " + error) 23 }); 24 } 25 1 26 2 27 3 28 4 29 5 30 6 31 7 32 8 33 9 34 10 35 11 36 12 37 13 38 14 39 15 40 16 41 17 42 18 43 19 44 20 45 21 46 22 47 23 48 24 49 第二種: form表單形式 50 /* 51 * post請求 52 * url:請求地址 53 * params:參數,這裏的參數要用這種格式:'key1=value1&key2=value2' 54 * callback:回調函數 55 * */ 56 static postForm(url,params,callback){ 57 //fetch請求 58 fetch(url,{ 59 method: 'POST', 60 headers: { 61 'Content-Type': 'application/x-www-form-urlencoded', 62 }, 63 body: params 64 }) 65 .then((response) => response.json()) 66 .then((responseJSON) => { 67 callback(responseJSON) 68 }) 69 .catch((error) => { 70 console.log("error = " + error) 71 }); 72 }
1 //post請求 2 let params = {'key1':'value1','key2':'value2'}; 3 NetRequest.postJSON('http://www.baidu.com/',params,function (set) { 4 //下面的就是請求來的數據 5 console.log(set) 6 }) 7 8 //get請求,以百度爲例,沒有參數,沒有header 9 NetRequest.get('https://www.baidu.com/','',function (set) { 10 //下面是請求下來的數據 11 console.log(set) 12 })
解釋一下:網絡
//將
JSON
數據轉換成字符串
JSON.stringify(params)app//將數據JSON化
JSON.parse(responseJSON)函數