node.js中的路由初步

1、建立n4_root.js

var    http    =    require('http');
var    url    =    require('url'); //这是node.js中自带的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;
                //request.url就拿到了输入框中的url
                //console.log(pathname);
                pathname    =    pathname.replace(/\//,    '');//替换掉前面的/
                //console.log(pathname);
                router[pathname](request,response);
                response.end('');
        }
}).listen(8888);
console.log('Server    running    at    http://127.0.0.1:8888/');   
 通过var    pathname    =    url.parse(request.url).pathname;是获得根目录的路径  http://127.0.0.1:8888(根目录)是个/


通过pathname = pathname.replace(/\//, '');//替换掉前面的/ 并且输入http://127.0.0.1:8888/login 会显示login

拿到login之后就可以进行之后的操作
新建一个router.js
module.exports={
    login:function(req,res){
        res.write("我是login方法");
    },
    zhuce:function(req,res){
        res.write("我是注册方法");
    }
} 
 

调用之后的结果是这样的

 

猜你喜欢

转载自www.cnblogs.com/xingyue1988/p/8876017.html