一、創建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