【问题标题】:Serving pages with Express and allowing file include使用 Express 服务页面并允许文件包含
【发布时间】:2016-07-15 15:10:23
【问题描述】:

我目前正在使用 Express 和 Angular 构建一个多页面应用程序。我已经像这样设置了我的文件夹结构:

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,我可以理解,但我不确定如何允许页面在其文件夹中包含文件?

任何建议将不胜感激:)

【问题讨论】:

    标签: javascript angularjs node.js express routing


    【解决方案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 将提供来自 folder2 的文件,您只需通过 website.com/folder2/file 获取它们,当您转到 website.com/otherPage 时,它​​会为您提供 /otherPage.html诸如此类。

    【讨论】:

    • 我必须为“文件夹 1”和“文件夹 2”使用哪些文件夹?
    • 您将为初学者提供 pageFolder,如果您有更多资产要以静态方式提供服务,则应以这种方式提供服务。我对 Angular 了解不多,所以我无能为力。
    猜你喜欢
    • 2013-07-15
    • 2011-05-27
    • 1970-01-01
    • 2013-10-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-14
    • 1970-01-01
    相关资源
    最近更新 更多