node.js中的路由(url)初步

一、创建n4_root.jshtml

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("我是注册方法");
    }
} 
 

调用以后的结果是这样的node

相关文章
相关标签/搜索