n4_rout.js

var http = require('http');

var url = require('url');
var router = require('./models/router.js');

http.createServer(function(request,response){
response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'});
if(request.url!=="/favicon.ico"){
//获取url后面的路径
var pathname = url.parse(request.url).pathname;
//console.log(pathname);
pathname = pathname.replace(/\//,'');//替换掉前面的/
//console.log(pathname);
router[pathname](request,response);
response.end('');
}
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');

./models/router.js:

module.exports={
login:function(req,res){
res.write("I am login function");
},
register:function(req,res){
res.write("I am register function");
}
}

运行效果:

node.js学习之路由初步_node.js

node.js学习之路由初步_node.js_02