node.js中的路由(url)初步
阿新 • • 發佈:2018-04-18
UC out root 目錄 port name login 方法 是個
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("我是註冊方法"); } }
調用之後的結果是這樣的
node.js中的路由(url)初步