Nodejs路由初步

基本思路:获取一个url,到server.js去解析,用正则表达式从pathname中解析出根目录后面的东西,在route.js中去写了相应的函数方法,调用即可。

//---------n4_rout.js-----------
var http =  require('http');
var url =  require('url');
var router  = require('./router');
http.createServer(function(request, response)    {
        response.writeHead(200,    {'Content-Type': 'text/html; charset=utf-8'});
        if(request.url!=="/favicon.ico"){
                var pathname =url.parse(request.url).pathname;
                pathname = pathname.replace(/\//, '');//替换掉前面的/
                router[pathname](request,response);
                response.end('');
        }
}).listen(8000);
console.log('Server    running    at    http://127.0.0.1:8000/');    
//-----------------router.js--------------------------------
module.exports={
    login:function(req,res){
        res.write("我是login方法");
    },
    zhuce:function(req,res){
        res.write("我是注册方法");
    }
}

你可能感兴趣的:(Nodejs路由初步)