1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | /* * post请求方法(推荐) * objUrl obj 主机名,路径 * objParam obj 附加数据对象 */ function requestPost(objUrl, objParam) { var http = require( 'http' ); //载入https模块 var qs = require( 'querystring' ); //载入Query String模块 var fs = require( 'fs' ); //载入fs模块读取文件 var content = qs.stringify(objParam); //url编码参数 var options = { hostname: objUrl.hostname, port: 80, path: objUrl.path, method: 'POST' , headers: { 'Content-Type' : 'application/x-www-form-urlencoded; charset=UTF-8' } }; var reqCallBack = function (res) { console.log( 'STATUS: ' + res.statusCode); console.log( 'HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding( 'utf8' ); res.on( 'data' , function (chunk) { //有数据时读数据 console.log( 'POST返回结果: ' + chunk); }); }; var req = http.request(options, reqCallBack); req.write(content); //POST方法传输数据 req.on( 'error' , function (e) { console.log( 'problem with request: ' + e.message); }); req.end(); } /* * get请求方法 * objUrl obj 主机名,路径 * objParam obj 附加数据对象 */ function requestGet(objUrl, objParam) { var http = require( 'http' ); //载入http模块 var qs = require( 'querystring' ); //载入Query String模块 var fs = require( 'fs' ); //载入fs模块读取文件 var content = qs.stringify(objParam); //url编码参数 var options = { hostname: objUrl.hostname, port: 80, path: objUrl.path + '?' + content, method: 'GET' }; var reqCallBack = function (res) { console.log( 'STATUS: ' + res.statusCode); console.log( 'HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding( 'utf8' ); res.on( 'data' , function (chunk) { //有数据时读数据 console.log( 'GET返回结果: ' + chunk); }); }; var req = http.request(options, reqCallBack); req.on( 'error' , function (e) { console.log( 'problem with request: ' + e.message); }); req.end(); } /* * * @requestType string 请求方式,POST或者GET,推荐POST */ function getContent(requestType) { var objUrl = { hostname: 'v.1dq.com' , //主机名 path: '/api/a137' , //api路径 } var objParam = { 'key' : '您申请的key,在会员中心->我的数据->对应数据的下方' , 'bankcard' : '' , 'bankname' : '' , 'province' : '' , 'city' : '' , 'district' : '' , 'keyword' : '' , 'page' : '' , } if (requestType == 'GET' ){ requestGet(objUrl,objParam); } else { requestPost(objUrl,objParam); } } console.log( 'Hello,www.APIStore.cn' ); getContent( 'POST' ); |