nodejs http request调用rpc接口

var data = {"jsonrpc": "2.0", "id": 0, "method": method, "params": params};
	data = JSON.stringify(data);
	var opt = {
	    host: ip,
	    port: port,
	    method: 'POST',
	    path:'/rpc',
	    headers:{
	        "Content-Type": 'application/json',
	        "Accept": 'application/json',
	        "Content-Length": data.length
	    }
	}
	 
	var request = http.request(opt, function(result) {
		var rpcResult = '';
		var datas = '';
		result.on('data',function(data) {
			try {
				datas += data;  // 注意:返回json数据量大时,会截取分批返回
			} catch(e) {
				console.log(e);
			}
	    }).on('end', function(){
	    	rpcResult = JSON.parse(datas).result; 
	    	resolve(rpcResult);
	    });
	}).on('error', function(e) {
	    console.log("error: " + e.message);
	    reject(e);
	});

	request.write(data);
	request.end();

注意的坑,返回json数据量大,会截取分批返回,所以在回调里定义了一个string执行++, 这个一定要注意

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

猜你喜欢

转载自blog.csdn.net/u012491783/article/details/81566326