2011-02-02 109 views
0

我試圖創建一個基於正則表達式匹配調用函數的Web服務器。下面是一個例子。但是,我無法調用匹配函數。此代碼會導致node.js崩潰,說對象方法不是函數。我究竟做錯了什麼?基於表達式的Web服務器

http = require "http" 

http.createServer((req, res) -> 
    res.writeHead 200, {"Content-Type": "text/plain"} 
    res.end handle req 
).listen 8080 

console.log "Server running at http://127.0.0.1:8080/" 

paths = [ 
    method: home, expression: "/" 
    method: user, expression: "/user" 
] 

home = (req) -> 
    return "This is the home" 

user = (req) -> 
    return "This is a user page" 

handle = (req) -> 
    for path in paths 
     if req.url.match path.expression 
      console.log path.expression 
      return path.method req 

回答

2
  • home/user在創建paths的時間沒有被定義。
  • paths不會是這種方式的對象數組。 (見FAQ

嘗試:

http = require "http" 

http.createServer (req, res) -> 
    res.writeHead 200, "Content-Type": "text/plain" 
    res.end handle req 
.listen 8080 

console.log "Server running at http://127.0.0.1:8080/" 

home = (req) -> "This is the home" 
user = (req) -> "This is a user page" 

paths = [ 
    {} = method: home, expression: "/" 
    {} = method: user, expression: "/user" 
] 

handle = (req) -> 
    for path in paths 
     if req.url is path.expression 
      console.log path.expression 
      return path.method req