优秀的编程知识分享平台

网站首页 > 技术文章 正文

HTTP网络请求模块(http网络稳定性要求是什么)

nanyue 2024-08-03 18:05:34 技术文章 6 ℃

一个精简的HTTP网络模块,可以进行POST或GET请求,可以指定请求头,兼容性很好

var http = {};
module.exports = http;
var stringifyQueryString = function (params) {
 var qs = '';
 for (var i in params) {
 if (params[i] !== undefined) {
 if (typeof params[i] === 'string') {
 qs += '&' + i + '=' + encodeURIComponent(params[i]);
 } else {
 qs += '&' + i + '=' + encodeURIComponent(JSON.stringify(params[i]));
 }
 }
 }
 return qs.slice(1);
};
/**
 * @param {url:string, data:any, tamethod:'post'|'get', timeout:number, headers:object} option
 */
http.quest = function (option, callback) {
 // 请求类型
 var method = option.method || 'GET';
 // 超时时间
 var timeout = option.timeout || 5000;
 // 请求头
 var headers = option.headers || { "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8" }; // application/json text/plain
 // 请求网址和数据
 var url = '';
 var data = null;
 if (method === 'post' || method === 'POST') {
 url = option.url;
 data = option.data;
 } else if (option.data) {
 url = option.url + '?' + stringifyQueryString(option.data);
 } else {
 url = option.url;
 }
 // 请求实例
 var xhr = new XMLHttpRequest();
 xhr.open(method.toLocaleLowerCase(), url, true);
 // 设置请求头
 for (var key in headers) { xhr.setRequestHeader(key, headers[key]) }
 // 设置超时时间
 (timeout > 0) && (xhr.timeout = timeout);
 // 发送请求
 xhr.send(((data !== null && typeof data === 'object') || typeof data === 'number' || typeof data === 'boolean') ? JSON.stringify(data) : data);
 // 请求返回
 xhr.onreadystatechange = () => {
 if (xhr.readyState == 4) {
 if (xhr.status >= 200 && xhr.status < 400) {
 var result = xhr.responseText;
 try { result = JSON.parse(xhr.responseText); } catch (e) { }
 callback && callback(null, result);
 } else {
 callback && callback('status: ' + xhr.status);
 }
 callback = null;
 }
 };
 xhr.ontimeout = function () {
 if (callback) {
 callback('timeout');
 callback = null;
 console.log('[sdk] %c连%c接%c超%c时 %s', 'color:red', 'color:orange', 'color:purple', 'color:green', url);
 }
 };
 xhr.onerror = function () {
 if (callback) {
 callback('error');
 callback = null;
 console.log('[sdk] %c连%c接%c失%c败 %s', 'color:red', 'color:orange', 'color:purple', 'color:green', url);
 }
 };
 xhr.onabort = function () {
 if (callback) {
 callback('abort');
 callback = null;
 console.log('[sdk] %c连%c接%c终%c止 %s', 'color:red', 'color:orange', 'color:purple', 'color:green', url);
 }
 };
 if (timeout) {
 setTimeout(() => {
 if (callback) {
 xhr.ontimeout();
 xhr.abort();
 }
 }, timeout);
 }
};
/**
 * http.get('login?code=asdi1239028sadadhjk213h',function(){})
 * http.get({url:'login',data:{code:'asdi1239028sadadhjk213h'}},function(){})
 * 
 */
http.get = function (url, callback, verification) {
 var option = url.url ? url : { url: url };
 option.method = 'get';
 this.quest(option, function (err, res) {
 if (!err && verification) {
 err = verification(res);
 }
 callback && callback(err, res);
 });
};
/**
 * http.post('login',function(){})
 * http.post({url:'login',data:{code:'asdi1239028sadadhjk213h'}},function(){})
 */
http.post = function (url, callback, verification) {
 var option = url.url ? url : { url: url };
 option.method = 'post';
 this.quest(option, function (err, res) {
 if (!err && verification) {
 err = verification(res);
 }
 callback && callback(err, res);
 });
};

最近发表
标签列表