2017-01-31 31 views
0

指定基本路徑下的作品如何使用的RESTify

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

我可以導航到HTTP:本地主機:8080和位於內側的靜態頁面/ myPublic顯示在瀏覽器中。

現在我想改變路線,以便我可以導航到 http:localhost:8080/test。因此我改變了上面的代碼

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

不行的,錯誤是

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

如何使它工作?

回答

1

tl; dr;

我錯誤地認爲一個url /測試/不管/路徑代表一個抽象的虛擬動作(類似於ASP.NET MVC路由),而不是在服務器上具體的物理文件。不是這樣的情況。

restify的工作原理是,對於靜態資源,無論您在url上輸入什麼,它都必須存在於服務器上的磁盤上,從'directory'中指定的路徑開始。 因此,當我請求本地主機:8080 /測試,我實際上尋求磁盤上的資源/myPublic/test/testPage.html;如果我輸入localhost:8080/test/otherPage.html,我實際上是在磁盤上尋找資源/myPublic/test/otherPage.html

細節:

隨着第一條路線

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

正則表達式 '*' 表示匹配任何內容!因此,在瀏覽器中我可以輸入 本地主機:8080/本地主機:8080/testPage.html本地主機:8080/otherPage.html本地主機:8080 /不管/ testPage.html本地主機: 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請求本地主機:8080 /測試,它將在公共/測試/ testPage服務上盤的默認頁面。html

爲了使處理更靈活,我可以使用正則表達式

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

這個表達式表示匹配「/測試」後跟任意字符(。)0次或多次(*),然後是斜線(/),後面跟着任何字符0次或更多次。例子可以是本地主機:8080 /測試/本地主機:8080 /睾丸/本地主機:8080 /睾丸/本地主機:8080 /測試/ otherPage.html本地主機:8080 /睾丸/ otherPage .HTML,以及設置存在磁盤上的路徑+各個文件,例如/public/test/testPage.html,/public/testis/testPage.html,/public/testicles/otherPage.html等那麼他們將被提供給瀏覽器。

0

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

/\/test\// 
+0

是的,我想正則表達式還張貼問題之前,但沒有奏效。我已經做了進一步的實驗,並會很快發佈答案。在我的愚見中,路線在restify中的概念被打破了。 – joedotnot