var http = require('http') ; var fs = require('fs'); var url = require('url'); var querystring=require('querystring'); //定义类的创建函数及全局类名 var ClassAPI={}; var newClassAPI = function (callback) { ClassAPI = (function (mod) { callback(mod); return mod; })(ClassAPI); }; newClassAPI(function (mod) { mod.GET={}; mod.POST={}; mod.get= function (p,callback) { mod.GET[p]=p; mod['GET'+p]= function (arg) { callback(arg); }; }; mod.post= function (p,callback) { mod.POST[p]=p; mod['POST'+p]= function (arg) { callback(arg); }; }; mod.reqType= function (type,pathname,ret,req,res) { if(req.method.toUpperCase()==type){ if(mod[type][pathname]==pathname){ mod[type+pathname]({ret:ret,req:req,res:res}); }else{ res.writeHeader(200,{'Content-Type' : 'text/plain;charset=utf-8'}) ; res.end("000") ; } } } }); newClassAPI(function (mod) { //定义class的方法 mod.fs_appendFile_log=function(t){ fs.appendFile('tree.txt', t+'\r\n', function (err) { if (err) throw err; // console.log(t); }); }; mod.getClientIP2=function(req){ var ipAddress; var headers = req.headers; var forwardedIpsStr = headers['x-real-ip'] || headers['x-forwarded-for']; forwardedIpsStr ? ipAddress = forwardedIpsStr : ipAddress = null; if (!ipAddress) { ipAddress = req.connection.remoteAddress; } return ipAddress; }; mod.req= function (req) { return { time:new Date().getTime(), type:req.method.toUpperCase(), host:req.headers.host, ip:req.connection.remoteAddress.split(":")[3], pathname:url.parse(req.url,true).pathname.substr(1), query:url.parse(req.url,true).query }; }; mod.http= function (req,res) { res.writeHeader(200,{'Content-Type' : 'text/plain;charset=utf-8'}) ; var pathname=url.parse(req.url,true).pathname; var Jret=JSON.stringify(mod.req(req)); if(pathname!='/favicon.ico'){ mod.fs_appendFile_log(Jret); res.end(Jret) ; } }; mod.server= function (v) { http.createServer(function (req,res) { var pathname=url.parse(req.url,true).pathname.substr(1); if(pathname!='favicon.ico'){ var ret=mod.req(req); var Jret=JSON.stringify(ret); mod.fs_appendFile_log(Jret);//记录每次请求 mod.reqType('GET',pathname,ret,req,res);//判断并执行GET请求 mod.reqType('POST',pathname,ret,req,res);//判断并执行POST请求 } }).listen(v); } }); module.exports = ClassAPI;
var app = require('./ClassAPI') ; //配置表 var config={ listen:8888 }; app.server(config.listen); app.get("index.html", function (arg) { console.log(arg.ret); arg.res.end(JSON.stringify(arg.ret.query.callback)); }); app.get("222", function (arg) { console.log(JSON.stringify(arg.res)); arg.res.end(JSON.stringify(arg.ret.query.callback)); }); app.get("3333", function (arg) { console.log(JSON.stringify(arg.ret)); arg.res.end(JSON.stringify(arg.ret.query.callback)); });
nodejs 实现get和post
最新推荐文章于 2024-07-29 11:17:05 发布