【问题标题】:Cannot include JS files in ExpressJS served index file不能在 ExpressJS 提供的索引文件中包含 JS 文件
【发布时间】:2016-09-06 17:48:06
【问题描述】:

我目前正在构建一个包含多个页面的 Web 应用程序。然而,这些页面中的每一个都有多个视图。最初的设计是将每个页面设置为 SPA,只从 Node.js 后端提供index.html,让 React.js 处理所有视图路由。

事实证明,这比我想象的要复杂。这就是问题所在。

Node.js 路由 (sn-p):

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

然后在index.html (sn-p):

<html>
<head>
    <title>New Website</title>
</head>
<body>

    <h1>Welcome to my website..</h1>

    <div id="App">
    </div>

    <script src="index.js"></script>
</body>
</html>

index.js 不包括在内。当浏览器尝试包含 index.js 时,它会从显然未设置的 Node.js 服务器请求路由 www.example.com/index.js,因此我收到了 Cannot GET /index.js 响应。

每个 SPA 都位于其各自的文件夹中,分别为 index.htmlindex.js。目前还不能创建一个包含所有 js 文件的公用文件夹。

================================================ =============================

已解决:这是我使用的代码

clientController.js

module.exports = function(app){
    router.get("/", function(request, response){
        app.use("/", express.static(__dirname + "/../client/pages/page1/"));
        response.sendFile("index.html", {
            root: __dirname + "/../client/pages/page1/"
        });
    });

    router.get("/page2/*", function(request, response){
        app.use("/", express.static(__dirname + "/../client/pages/page2/"));
        response.sendFile("index.html", {
            root: __dirname + "/../client/pages/page2/"
        });
    });

    return router;
};

server.js

var routes = require("controllers/clientController.js");
app.use("/", routes);

接受的答案,我还必须在sendFile() 行中添加以防止请求挂起。这会解决响应并允许在 HTML 文件中包含文件的正确路径。

【问题讨论】:

  • 您需要确保您的express 启用了静态目录模块。此外,如果它是真正的 SPA,您可以将 HTML 和 API 分离到单独的项目中。
  • 整个项目不是SPA。有多个页面,我将每个页面设置为 SPA,因为它们每个都有 3/4 视图。
  • 你不需要把app.use(...)放到router.get(...)中。这将在您每次提出请求时产生开销。
  • @bilalba 没有 app.use() 我的问题没有解决?
  • 我的意思是,把那些写在router.get(...)之外就行了

标签: javascript html node.js


【解决方案1】:

正如ExpressJs documentation 中提到的,您必须使用express.static(root, [options]) 创建一个中间件来管理您的网站。这是 Express 中唯一内置的中间件功能。

快递应用示例:

在你必须初始化你的应用程序之前:

var express = require('express');
var app = express();

然后你开始添加你的中间件:

注意:您可以添加多个中间件,并按顺序链接它们。换句话说,您可以在网站中间件之前添加标头处理程序。

Headers 中间件处理程序示例:

app.use(function (req, res, next) {
    /* you can also handle https redirection */
    // if (req.protocol != "https") {
    //     res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url});
    //     res.end();
    //     return;
    // }

    // here you can config you response headers
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');


    next(); // this will pass the request to the next middleware  
});

网站路由器示例:

要使用 ExpressJs 创建中间件网站,您必须将 express.static 与您的相关网站文件夹一起使用,并将默认页面命名为 index.html

app.use("/", express.static('PATH_TO_WEBSITE FOLDER'));

完整的 ExpressJs 应用示例:

var express = require('express');
var app = express();

app.use(function (req, res, next) {
    /* you can also handle https redirection */
    // if (req.protocol != "https") {
    //     res.writeHead(301, {"Location": "https://" + req.headers['host'] + req.url});
    //     res.end();
    //     return;
    // }

    // here you can config you response headers
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    res.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');


    next(); // this will pass the request to the next middleware  
});


app.use("/", express.static('PATH_TO_WEBSITE FOLDER'));


var httpServer = http.createServer(app);
httpServer.listen(80, "HERE_PUT_YOUR_DOMAIN", function () {
    console.log('HTTP: express-example running on port ' + 80 + '.');
});

【讨论】:

    【解决方案2】:

    您的目录将被视为静态目录。您不需要创建单独的目录或定义单独的路由。

    router.use(express.static( __dirname + "/../client/pages/home/"));
    

    【讨论】:

    • 我必须为每个页面的每个包含编写一个路由。
    • 这是不可能的@bilalba。我必须为每个包含制作一条路线。这会太多,而且会适得其反。
    • 是的,对不起。答案并不令人耳目一新。
    猜你喜欢
    • 1970-01-01
    • 2011-10-13
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 2021-09-23
    • 1970-01-01
    • 2017-08-06
    • 2015-08-07
    相关资源
    最近更新 更多