node.js中使用路由方法

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‘,res) {
  res.write("我是注册方法");
  console.log(102);
}});

myrouter_action.push({ xpath:  ‘/logout‘,res) {
  res.write("我是注销方法");
  console.log(103);
}});


myrouter_action.push({ xpath:  ‘/‘,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));

相关文章

这篇文章主要介绍“基于nodejs的ssh2怎么实现自动化部署”的...
本文小编为大家详细介绍“nodejs怎么实现目录不存在自动创建...
这篇“如何把nodejs数据传到前端”文章的知识点大部分人都不...
本文小编为大家详细介绍“nodejs如何实现定时删除文件”,内...
这篇文章主要讲解了“nodejs安装模块卡住不动怎么解决”,文...
今天小编给大家分享一下如何检测nodejs有没有安装成功的相关...