node 请求
2015-12-17 11:05
661 查看
入口文件调用
http.js文件
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(); };
相关文章推荐
- 探秘ajax跨域请求
- Windows系统下Node.js的简单入门教程
- 在Node.js应用中使用Redis的方法简介
- 在Ubuntu系统上安装Ghost博客平台的教程
- Node.js编程中客户端Session的使用详解
- 使用Raygun对Node.js应用进行错误处理的方法
- 在Mac OS下使用Node.js的简单教程
- node.js抓取并分析网页内容有无特殊内容的js文件
- 浅析Node在构建超媒体API中的作用
- 在Node.js中使用HTTP上传文件的方法
- 举例讲解Node.js中的Writable对象
- PHP实现支持GET,POST,Multipart/form-data的HTTP请求类
- Node调试工具JSHint的安装及配置教程
- Node.js实现简单聊天服务器
- 浅析Node.js中使用依赖注入的相关问题及解决方法
- Jquery Ajax请求方法小结(值得收藏)
- Ajax在请求过程中显示进度的简单实现
- jquery中AJAX请求 $.post方法的使用
- Javascript跨域请求的4种解决方式