您的位置:首页 > Web前端 > Node.js

node 请求

2015-12-17 11:05 661 查看
入口文件调用


var _http = require('./http.js');
require('./login.js')(app, _http);

http.js文件

var http = require('http');
var https = require('https');
var util = require('util');

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"; // https请求

/*
* GET
* url 访问路径
*      '/a/company/list?sid=sid'
* fun 回调方法
*      function(cont),cont返回的数据
*/
exports.GET = function(url, fun) {
var cont = '',
url = 'http://tpos.yingzixia.com' + url;
http.get(url, function(res) {
res.setEncoding('utf-8');
res.on('data', function(chunk) { cont += chunk; });
res.on('end', function() {
fun(cont);
});
}).on('error', function(err) {
console.log("Got error: " + err.message);
});
};

/*
* POST
* postData 传递参数
*      {
*          'account': name,
*          'passwd': md5(passwd)
*      }
* url 访问路径
*      '/a/app/login'
* fun 回调方法
*      function(cont),cont返回的数据
*/
exports.POST = function(postData, url, fun) {
var querystring = require('querystring');
postData = querystring.stringify(postData);
var cont = '',
options = {
hostname: 'tpos.yingzixia.com',
path: url,
port: 80,
method: 'POST',
headers: {
'Content-Length': postData.length,
'Content-Type': 'application/x-www-form-urlencoded'
}
},
req = http.request(options, function(res) {
res.on('data', function(chunk) { cont += chunk; });
res.on('end', function() {
try {
cont = JSON.parse(cont);
fun(cont);
} catch (e) {
fun(cont);
}
});
});
req.on('error', function(e) {
console.log('Error: ' + e.messsage);
});
req.write(postData);
req.end();
};

/*
* HTTPS POST请求
*/
exports.POST2 = function(postData, url, fun) {
var querystring = require('querystring');
postData = querystring.stringify(postData);
var cont = '',
options = {
hostname: 'tpos.yingzixia.com',
path: url,
port: 443,
method: 'POST',
headers: {
'Content-Length': postData.length,
'Content-Type': 'application/x-www-form-urlencoded'
}
},
req = https.request(options, function(res) {
res.on('data', function(chunk) { cont += chunk; });
res.on('end', function() {
try {
cont = JSON.parse(cont);
fun(cont);
} catch (e) {
fun(cont);
}
});
});
req.on('error', function(e) {
console.log('Error: ' + e.messsage);
});
req.write(postData);
req.end();
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  node 请求