node.js中使用路由方法

1.數組的find方法仍是不會用,改成filterhtml

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));
相關文章
相關標籤/搜索