node 發送get, post請求,支持http和https

// 通用get請求(http, https)
var sendGetRequest = function(ip, port, path, headers, type) {
	
	return new Promise((resolve, reject) => {
			var opt = {
				host: ip,  // 這裏是ip(192.168.1.1)或者域名(mydomain.com),注意不能帶http://或https://
			    port: port,
			    method: 'GET',
			    path: path,
			    headers: headers
			}
			var req = null;
			var rpcResult = '';
			var datas = '';
			
			if (type == "http") {
				req = http.request(opt, function(result) {
					result.on('data', function(data) {
						console.log(data);
						try {
							datas += data;  // 注意:返回json數據量大時,會截取分批返回
						} catch(e) {
							console.log(e);
						} 
				    }).on('end', function(){
				    	if (datas != undefined && datas != null) {
				    		rpcResult = JSON.parse(datas); 
					    	resolve(rpcResult);
				    	} else {
				    		// 請求獲取不到返回值
				    		resolve("2");
				    	}
				    	
				    })
				});
			} else if (type == "https") {
				req = https.request(opt, function(result) {
					result.on('data', function(data) {
						try {
							datas += data;  // 注意:返回json數據量大時,會截取分批返回
						} catch(e) {
							console.log(e);
						} 
				    }).on('end', function(){
				    	if (datas != undefined && datas != null) {
				    		rpcResult = JSON.parse(datas); 
					    	resolve(rpcResult);
				    	} else {
				    		// 請求獲取不到返回值
				    		resolve("2");
				    	}
				    	
				    })
				});
			}
			
			req.on('error', function (e) {  
				// request請求失敗
			    console.log('請求失敗: ' + e.message); 
			    reject("0");
			});  
			req.end();
	})
	
}

// 通用post請求(http,https)
var sendPostRequest = function(ip, port, path, headers, type, params) {
	return new Promise ((resolve, reject) => {
		data = JSON.stringify(params);
		var opt = {
		    host: ip,
		    port: port,
		    method: 'POST',
		    path: path,
		    headers: headers
//		    headers:{
//		        "Content-Type": 'application/json',
//		        "Accept": 'application/json',
//		        "Content-Length": data.length
//		    }
		}
		
		var request = null;
		var rpcResult = '';
		var datas = '';
		if (type == "http") {
			
			request = http.request(opt, function(result) {
				
				result.on('data',function(data) {
					try {
						datas += data;  // 注意:返回json數據量大時,會截取分批返回
					} catch(e) {
						console.log(e);
					}
			    }).on('end', function(){
			    	rpcResult = JSON.parse(datas)
			    	resolve(rpcResult);
			    });
			}).on('error', function(e) {
			    console.log("error: " + e.message);
			    reject(e);
			});
		} else if (type == "https") {
			
			request = https.request(opt, function(result) {
				result.on('data',function(data) {
					try {
						datas += data;  // 注意:返回json數據量大時,會截取分批返回
					} catch(e) {
						console.log(e);
					}
			    }).on('end', function(){
			    	rpcResult = JSON.parse(datas)
			    	resolve(rpcResult);
			    });
			}).on('error', function(e) {
			    console.log("error: " + e.message);
			    reject(e);
			});
		}

		// 發送請求(post請求需要寫入參數)
		request.write(data);
		request.end();
	});
	
}

    

1. node發送get和post請求,注意opt裏面的ip一定是單獨的ip或者域名,不帶http://和https://的。

2. headers的傳入, 如果裏面定義的key是變量,比如調用某個數據提供商的api,需要他們賦予調用權限的secretKey,比如阿里的是aliSecretKey, 京東的是jdSecretKey,這時可以通過[]定義對象的方式,以便方法可以通用。如:

var headers = {};
headers[secretKey] = secretValue

3. 返回json數據量大,會截取分批返回,所以在回調裏定義了一個string執行++, 這個一定要注意

參考:

https://nodejs.org/api/http.html

https://nodejs.org/api/https.html

https://www.cnblogs.com/Gasg/p/8044889.html

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章