路由就是根據(jù)瀏覽器的url對應訪問不同的網(wǎng)頁
服務(wù)器拿到瀏覽器的url菌仁,根據(jù)正則匹配,拿到根目錄之后的字符串
有一個可能名字為route.js的匹配規(guī)則,根據(jù)字符串調(diào)用不同的方法
在方法里再去讀取相應的html文件聊倔,做相應的操作
04_route.js
var http = require('http');
var url = require('url');
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;
console.log(pathname);
pathname = pathname.replace(/\//, ''); //替換掉前面的/
console.log(pathname);
router[pathname](request, response);
response.end('');
}
}).listen(8000);
console.log('Server running at http://127.0.0.1:8000/');
router.js
module.exports = {
login: function(req, res) {
res.write("我是login方法");
},
zhuce: function(req, res) {
res.write("我是注冊方法");
}
}
注意晦毙,直接訪問localhost:8000會報錯,因為path是/耙蔑,沒有對應路由
需要訪問**localhost:8000/login