2016-02-29 52 views
0

我正在使用Restify來服務我的靜態網頁。 html文件調用腳本和css文件的服務器。使用默認前綴nodejs服務靜態html文件

,我創造需要有/安全前綴所有端點服務器/端點

我已經能夠服務器index.html文件,但是當瀏覽器嘗試包括腳本和CSS文件,我得到一個404狀態碼。

當我到localhost:1337/safe/endpoint時,我得到了正確呈現的index.html。但是當瀏覽器嘗試下載其他文件時,它會在index.html中以localhost:1337/safe代替localhost:1337/safe/endpoint的前綴。

例如:

中的index.html被送達這個路徑

localhost:1337/safe/endpoint 

index.html文件中我有這包括

<script src="app/js/thing.js"></script> 

當瀏覽器嘗試獲取thing.js使用此路徑

localhost:1337/safe/app/js/thing.js 

代替

localhost:1337/safe/endpoint/app/js/thing.js 

服務器代碼看起來像這樣

server.get("/safe/endpoint", function(req, res){ 
    fs.readFile("./frontend/index.html", "utf8", function(err, data){ 
    if(err){ 
     res.setHeader('content-type', 'text/plain'); 
     res.send(404, "No index.html found"); 
    } else { 
     res.setHeader('Content-Type', 'text/html'); 
     res.writeHead(200); 
     res.end(data); 
    } 
    }); 
}); 

server.get("/safe/endpoint/app/.*", function(req, res){ 
    var filePath = "./frontend" + req.url.split("/safe/endpoint")[1]; 

    fs.readFile(filePath, "utf8", function(err, data){ 
    if(err){ 
     res.setHeader('content-type', 'text/plain'); 
     res.send(404, req.url + " not found"); 
    } else { 
     res.setHeader('Content-Type', 'text/html'); 
     res.writeHead(200); 
     res.end(data); 
    } 
    }); 
}); 
+0

FYI:你可以做其他人一樣,使用從客戶方訪問的'/ public'文件夾,所有靜態文件的靜態路由,並且無論如何都不能訪問其他文件,不需要「安全/端點」。 – adeneo

+0

@ adeneo是儀式。 express.static文件夾並通過'/ public'服務是最好的方法。 – 2016-02-29 20:38:03

+0

我正在使用restify。由於restify.serveStatic中的功能,您可以爲靜態服務器定義一個基本目錄。那麼端點的路徑將成爲基礎目錄上的修補程序。要使用它,我需要創建一個文件夾結構(即frontent/safe/endpoint/app/js/thing.js而不是前端/ app/js/thing.js)。該文件夾結構是我想要避免的。 http://stackoverflow.com/questions/19281654/serving-static-files-with-restify – Thor

回答

1

我能夠獲得與serveStatic這方面的工作包括的RESTify模塊

server.get("/safe/endpoint/.*", restify.serveStatic({ 
    directory: "./UI", 
    default: "index.html" 
})); 

的,但我需要在UI文件夾中爲文件夾路徑加上前綴:

/UI/safe/endpoint/index.html 

但是這有一個缺點。當請求到服務器的路徑需要

example.com/safe/endpoint/ 

,而不是

example.com/safe/endpoint