node获取url地址
1 var http = require("http"); 2 var url = require('url');//node.js自带的url 3 var router = require('./router'); 4 5 http.createServer(function(request,response){ 6 response.writeHead(200,{'Content-Type':'text/html;charset=utf-8'}); 7 //一开始不加if,打印出的结果一直带favicon.ico,导致下面一直出错,加上这个判断好了 8 if(request.url!=='/favicon.ico'){ 9 var pathname = url.parse(request.url).pathname; //路径名称带‘/’ 10 pathname=pathname.replace(///,''); //替换'/' 11 console.log(pathname); 12 //调用router中方法 13 router[pathname](request,response); 14 response.end(''); 15 } 16 }).listen(8000); 17 18 console.log("server at running http://127.0.0.1:8000");
router.js
1 module.exports={ 2 login:function(req,res){ 3 res.write("我是login方法"); 4 }, 5 register:function(req,res){ 6 res.write("我是register方法"); 7 } 8 }
在浏览器输入:localhost:8000/login 打印出 “我是login方法”
localhost:8000/register 打印出“我是register方法”