2016-01-15 136 views
0

我有下面的代碼,而path真的很讓人困惑。 restify的api指南沒有太多解釋。restify路徑路徑含義

const restify = require('restify'); 

const app = restify.createServer(); 

app.get(/\/path\/.*/, function(req,res,next){ 
    console.log('regexp'); 
    return next(); // suppose to pass control to next handler, but nothing happended. 
}) 

// it seems that '/path/:name' has the same meaning of /\/path\/.*/. Did I miss something? 
app.get('/path/:name', function(req,res,next){ 
    console.log('colon') 
    return next();// still not pass control to next handler 
}) 

// those two works as expected. 
app.get('/path/first', function(req,res,next){ 
    res.end('first'); 
}) 

app.get('/path/second', function(req,res,next){ 
    res.end('second'); 
}) 

app.listen(80, function() { 
    console.log('Server is running'); 
}); 

那麼有人可以向我解釋這些路徑的確切含義嗎?我怎樣才能使next()工作?

回答

0

爲了回答這個問題,我會帶你通讀代碼並評論實際發生的事情。正如您已經理解的,這些路由適用於您的服務器的GET請求。

第一條路線是尋找'/ path/*'中的任何請求。只要領先的'/ path /'存在,它將接受大多數值。 next()用於提供訪問鏈中下一個處理程序的權限,通常用於創建中間件,但有其他用途。

app.get(/\/path\/.*/, function(req,res,next){ 
    console.log('regexp'); 
    return next(); 
}) 

這第二條路由與第一條路由類似,它接受'/ path/*'上的任何內容。然而,這裏的區別在於,第二個斜槓'/:id'之後的anythign將作爲變量存儲在req.params中。例如,點擊'/ path/12'會將12存儲在req.params.id中。訪問'/ path/bar'會將條存儲在req.params.id中。

app.get('/path/:name', function(req,res,next){ 
    console.log('colon') 
    return next(); 
}) 

另外兩條路徑是不言自明的。他們走上一條道路並採取相應行動。你正在嘗試使用next()來做什麼?

+0

假設我發送了一個請求,比如說'/ path/first'。我不想通過'/ \/path \ /.*/',''/ path /:name''和''/ path/first''來處理。我認爲next()會以這種方式工作,但實際上,只有'/ \/path \ /.*/'處理程序會被執行。 – agsonoo

+0

它將使用它找到的第一個匹配項。就我所知,下一步()不能以這種方式工作。 – hudsond7

0

這給你一個想法是什麼未來用於...

// log debug message on each request 
server.use(function request(req, res, next) { 
    logger.debug(req.method, req.url); 
    return next(); 
}); 

// validate jwt 
server.use(function request(req, res, next) { 
    // validate web token here ... if invalid then respond 401 (unauthorised) else do a next ... 
    return next(); 
}); 

app.get('/path/first', function(req,res,next){ 
    // return a response don't call next here 
}) 

也,在你的代碼中使用res.end - 不熟悉的(但也可能存在) - 但沒有你的意思是調用res.send?