1.数组的find方法还是不会用,改为filter 2.正规表达式还是理解的不好 // var myrouter = require("./myrouter"); // myrouter.getRouteValue(‘login‘)(1,2); pathname = ‘/login‘ pathname = pathname.replace(/\//, "");
1.数组的find方法还是不会用,改为filter
2.正规表达式还是理解的不好
//var myrouter = require("./myrouter"); //myrouter.getRouteValue(‘login‘)(1,2); pathname = ‘/login‘ pathname = pathname.replace(/\//, ""); //替换掉前面的/ console.log(‘\/‘); //输出/ console.log(‘/‘); ////输出/ console.log(pathname); // 语法: 依据 两侧一个//作为模式界定 /pattern/attributes // 解析: 两侧的/ /,为模式界定符; 中间的\/表示/,也就是/login中的/
var myrouter_action = []; myrouter_action.push({ xpath: ‘/login‘, yvalue: function(req, res) { res.write("我是登录方法"); console.log(101); }}); myrouter_action.push({ xpath: ‘/register‘, yvalue: function(req, res) { res.write("我是注册方法"); console.log(102); }}); myrouter_action.push({ xpath: ‘/logout‘, yvalue: function(req, res) { res.write("我是注销方法"); console.log(103); }}); myrouter_action.push({ xpath: ‘/‘, yvalue: function(req, res) { res.write("我是根目录方法"); console.log(100); }}); /* 从arr中寻找标志为opath的函数 */ function getRouteValue(opath) { var filterArray = myrouter_action.filter(function(v) { return v.xpath === opath }) if (filterArray.length) { return filterArray[0].yvalue }else{ console.log(‘查找路由表失败!‘, opath); } } module.exports={ getRouteValue }
var http = require("http"); var url = require("url"); var myrouter = require("./myrouter"); http .createServer(function(request, response) { response.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); if (request.url !== "/favicon.ico") { console.log("1:",request.url); var pathname = url.parse(request.url).pathname; //得到请求的路径 console.log("2:",pathname); //pathname = pathname.replace(/\//, ""); //替换掉前面的/ //console.log("2",pathname); //myrouter.getRouteValue(pathname)(request, response); myrouter.getRouteValue(pathname)(request, response); response.end(""); } }) .listen(8000); console.log("Server running at http://127.0.0.1:8000/"); //console.log(myrouter.getRouteValue(‘login‘)(1,2));