声明:在写nodejs代码的时候,很多模块可以封装保存起来,以后的项目都会用到。
1、路由模块
var url=require(‘url‘);//封装方法改变res ?绑定res.send()function changeRes(res){ ???res.send=function(data){ ???????res.writeHead(200,{"Content-Type":"text/html;charset=‘utf-8‘"}); ???????res.end(data); ???}}//暴露的模块var Server=function(){ ???var G=this; ??/*全局变量*/ ???//处理get和post请求 ???this._get={}; ???this._post={}; ???var app=function(req,res){ ???????changeRes(res); ???????//获取路由 ???????var pathname=url.parse(req.url).pathname; ???????if(!pathname.endsWith(‘/‘)){ ???????????pathname=pathname+‘/‘; ???????} ???????//获取请求的方式 get ?post ???????var method=req.method.toLowerCase(); ???????if(G[‘_‘+method][pathname]){ ???????????if(method==‘post‘){ /*执行post请求*/ ???????????????var postStr=‘‘; ???????????????req.on(‘data‘,function(chunk){ ???????????????????postStr+=chunk; ???????????????}) ???????????????req.on(‘end‘,function(err,chunk) { ???????????????????req.body=postStr; ?/*表示拿到post的值*/ ???????????????????G[‘_‘+method][pathname](req,res); /*执行方法*/ ???????????????}) ???????????}else{ /*执行get请求*/ ???????????????G[‘_‘+method][pathname](req,res); /*执行方法*/ ???????????} ???????}else{ ???????????res.end(‘no router‘); ???????} ???} ???app.get=function(string,callback){ ???????if(!string.endsWith(‘/‘)){ ???????????string=string+‘/‘; ???????} ???????if(!string.startsWith(‘/‘)){ ???????????string=‘/‘+string; ???????} ???????// ???/login/ ???????G._get[string]=callback; ???} ???app.post=function(string,callback){ ???????if(!string.endsWith(‘/‘)){ ???????????string=string+‘/‘; ???????} ???????if(!string.startsWith(‘/‘)){ ???????????string=‘/‘+string; ???????} ???????G._post[string]=callback; ???} ???return app;}module.exports=Server();
2、直接摘抄,然后创建一个文件运行下面的代码。
var http = require(‘http‘);var app = require(‘./express-route‘);http.createServer(app).listen(‘8001‘);app.get(‘login‘,function (req,res) { ???console.log(‘login‘); ???res.end(‘login‘);})app.get(‘register‘,function (req,res) { ???console.log(‘register‘); ???res.end(‘register‘);})
nodejs之路由
原文地址:https://www.cnblogs.com/ywjfx/p/10399967.html