一个APP开发,网络请求是必不可少的,在项目中我被分配到任务是网络请求参数的封装,所以本文主讲的是网络请求的封装。
先上代码,我再解释用法:
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
ListView,
Image,
TouchableOpacity,
Platform,
AsyncStorage,
Alert
} from 'react-native';
import CONFIG from './Config.js';
var NetUtil = {}
/* 使用Promise封装fetch请求 */
/**
* 让fetch也可以timeout
* timeout不是请求连接超时的含义,它表示请求的response时间,包括请求的连接、服务器处理及服务器响应回来的时间
* fetch的timeout即使超时发生了,本次请求也不会被abort丢弃掉,它在后台仍然会发送到服务器端,只是本次请求的响应内容被丢弃而已
* @param {Promise} fetch_promise fetch请求返回的Promise
* @param {number} [timeout=30000] 单位:毫秒,这里设置默认超时时间为30秒
* @return 返回Promise
*/
function timeout_fetch(fetch_promise, timeout = 30000) {
let abort_fn = null;
let abort_promise = new Promise(function(resolve, reject) {
abort_fn = function() {
reject('abort promise');
}
});
let abortable_promise = Promise.race([
fetch_promise,
abort_promise
]);
setTimeout(function () {
abort_fn();
}, timeout);
return abortable_promise;
}
/**
*
* @param {string} url 接口地址
* @param {string} method 请求方法:GET、POST,只能大写
* @param {JSON} [params=''] body的请求参数,默认为空
* @return 返回Promise
*/
function fetchRequest(url, method, params='') {
let header = {
"Content-Type": "application/json;charset=UTF-8",
}
if (params == '') {
return new Promise(function(resolve, reject) {
timeout_fetch(fetch(url,{
method: method,
headers: header,
})).then((response) => response.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((err) => {
reject(err);
});
});
}else {
return new Promise(function(resolve, reject) {
timeout_fetch(fetch(url,{
method: method,
headers: header,
body:JSON.stringify(params),
})).then((response) => response.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((err) => {
reject(err);
});
});
}
}
/**
* Get请求
* @param {string} url 接口地址
* @param {JSON} [params=''] 接口参数,默认为空
*/
NetUtil.getRequest = function(url, params='') {
return fetchRequest(url, 'GET', params);
}
/**
* Post请求
* @param {string} url 接口地址
* @param {JSON} params 接口参数,默认为空
*/
NetUtil.postRequest = function(url, params='') {
return fetchRequest(url, 'POST', params);
}
/**
* 测试:如果请求工具使用的API由Fetch变为XMLHttpRequest(俗称ajax)
App调用方式将不回发生改变。
*/
function XMLGetRequest(url, method, params='') {
return new Promise(function(resolve, reject) {
var request = new XMLHttpRequest();
request.onreadystatechange = (e) => {
if (request.readyState !== 4) {
return;
}
if (request.status === 200) {
console.log('yuqin');
resolve(request.responseText)
}else {
rejet('error');
}
};
request.open(method, url);
request.send();
});
}
module.exports = NetUtil;
1.首先写了个工具类,如果要使用先import
import NetUtil from '../comm/NetUtil';
2.调用方式
GET请求
方法名:getRequest
参数:url:接口url
params:请求入参,可不传
NetUtil.getRequest = function(url, params='') {
return fetchRequest(url, 'GET', params);
}
请求示例:
NetUtil.getRequest('https://facebook.github.io/react-native/movies.json')
.then(responseJson => {
console.log(responseJson);
}).catch(err => {
console.log(err);
});
返回结果如下:
Post请求几乎一样,换个postRequest方法名就行。