簡體   English   中英

如何使用restify指定基本路線

[英]how to specify basic routes with restify

以下作品

server.get('.*', restify.serveStatic({
    'directory': './myPublic',
    'default': 'testPage.html'
}));

我可以導航到http:localhost:8080,並在瀏覽器中顯示/ myPublic內部的靜態頁面。

現在,我想更改路由,以便可以導航到http:localhost:8080 / test 因此我將上面的代碼更改為

server.get('/test', restify.serveStatic({
    'directory': './myPublic',
    'default': 'testPage.html'
}));

不起作用,錯誤是

{
    "code": "ResourceNotFound",
    "message": "/test"
}

如何使其運作?

tl; dr;

我錯誤地假設url / test / whatever / path代表抽象的虛擬操作(類似於ASP.NET MVC路由),而不是服務器上的具體物理文件。 重新調整並非如此。

對於靜態資源,restify的工作方式是,無論您在url上鍵入什么內容,它都必須存在於服務器的磁盤上,並從“目錄”中指定的路徑開始。 因此,當我請求localhost:8080 / test時 ,我實際上是在磁盤上搜索/myPublic/test/testPage.html資源; 如果我鍵入localhost:8080 / test / otherPage.html ,則實際上是在磁盤上尋找資源/myPublic/test/otherPage.html

細節:

與第一條路線

server.get('.*', restify.serveStatic({
    'directory': __dirname + '/myPublic',
    'default': 'testPage.html'
}));

RegEx'。*'表示匹配任何內容! 因此,在瀏覽器中,我可以輸入localhost:8080 /localhost:8080 / testPage.htmllocalhost:8080 / otherPage.htmllocalhost:8080 / whatever / testPage.htmllocalhost:8080 / akira / fubuki /等GET請求最終將被路由到上述處理程序,並提供路徑/myPublic/testPage.html,/myPublic/otherPage.html,/myPublic/whatever/testpage.html,/myPublic/akira/fubuki/testpage.html ,等存在於磁盤上,該請求將得到滿足。

與第二條路線

server.get('/test', restify.serveStatic({
    'directory': __dirname + '/myPublic',
    'default': 'testPage.html'
}));

該處理程序將與get請求localhost:8080 / test匹配,並將為磁盤上的默認頁面public / test / testPage.html提供服務

為了使處理程序更加靈活,我可以使用RegEx

server.get(/\/test.*\/.*/, restify.serveStatic({
    'directory': __dirname + '/myPublic',
    'default': 'testPage.html'
}));

此RegEx表示匹配'/ test',后跟任何char(。)0或更多次(*),后跟斜杠(/),然后是0或更多次任何char。 示例可能是localhost:8080 / test /localhost:8080 / testis /localhost:8080 / testicles /localhost:8080 / test / otherPage.htmllocalhost:8080 / testicles / otherPage.html ,並提供了路徑+文件存在於磁盤上,例如/public/test/testPage.html、/public/testis/testPage.html、/public/testicles/otherPage.html等,然后將它們提供給瀏覽器。

看起來restify正在為路由尋找正則表達式,而不是字符串。 嘗試這個:

/\/test\//

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM