2016-07-15 18 views
0

我正在使用Express & Angular構建多頁應用程序。我建立了我的文件夾結構是這樣的:使用Express服務頁面並允許文件包括

project 
|- server.js (The webserver) 
|- routes.js (The routes to serve the html pages) 
| |- node_modules 
| |- config 
| |- controllers (The routes for the API) 
| |- models (The SQL models - Sequelizer 
| |- client 
|  |- client.js (AngularJS main module) 
|  |- pages (Splitting the pages into Angular SPA) 
|   |- pageFolder (One for each page) 
|   |- page.html (The template for this SPA) 
|   |- page.js (The AngularJS controller) 
|   |- views (The views for the page) 

我已經做了廣泛的研究,這似乎是一個很舒服的方法來組織一切。我的代碼中的API部分與客戶端上的AngularJS模塊一樣有魅力。我正在努力將兩者聯繫起來。

在我routes.js文件,我服了已經被請求的特定頁面索引文件 - 例如:

var express = require("express"); 
var router = express.Router(); 

router.get("/", function(request, response){ 
    response.sendFile("home.html",{ 
     root: "client/pages/home" 
    }); 
}); 

router.get("/otherPage", function(request, response){ 
    response.sendFile("otherPage.html",{ 
     root: "client/pages/otherPage" 
    }); 
}); 


module.exports = router; 

這是可以正常使用的文件,直到我開始嘗試到AngularJS模塊集成到網頁。我建立了一個到node_modules文件夾的靜態路由/resources,這使我可以在每個頁面中包含AngularJS和其他庫。該AngularJS控制器,然而,被放置在每個頁面的文件夾,而不是在一個集中的文件夾controllers,當我嘗試包括像這樣的例子控制器:

<script src="home.js"></script> 

服務器處理請求的http://website.com/home.js我可以理解,但我不知道如何讓頁面包含在其文件夾中的文件?

任何建議,將不勝感激:)

回答

1

你可以試試這個:

app.use(express.static('folder1')); 
app.use('/folder2', express.static('folder2')); 

router.get("/otherPage", function(request, response){ 
    response.sendFile(__dirname + "/otherPage.html"); 
}); 

這樣,website.com/folder2的任期將從文件夾2文件,你可以僅僅通過website.com獲得它們/ folder2/file,當你訪問website.com/otherPage時,它會給你/otherPage.html和類似的東西。

+0

我必須使用哪個文件夾作'folder1'和'folder2'? – nickcorin

+0

如果你有更多的資產以靜態的方式提供服務,你將爲首發者提供pageFolder,你應該以這種方式爲他們提供服務。我對角度瞭解不多,所以我無法再提供幫助。 – ardilgulez

相關問題