javascript - 不能在 ExpressJS 提供的索引文件中包含 JS 文件

标签 javascript html node.js

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

事实证明这比我想象的要复杂。问题来了。

Node.js 路由(片段):

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

然后在 index.html(片段)中:

<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 文件中包含的文件的正确路径。

最佳答案

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

express 应用示例:

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

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

然后开始添加中间件:

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

header 中间件处理程序示例:

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 + '.');
});

关于javascript - 不能在 ExpressJS 提供的索引文件中包含 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39331826/

相关文章:

javascript - 为什么这个 jQuery 在 Codeigniter 中不起作用?

javascript - 从不同地方取消setInterval(NodeJS变量范围)

mysql - nodejs mysql post方法返回一个旧的未知记录

javascript - 如何使用 JavaScript 获取视频标签 src?

jquery - 使用 jquery 在 div 上滚动时更改 anchor 类

javascript - 在 chrome 扩展中创建 HTML 对话框弹出窗口

html - 汉堡菜单下方几行的链接文本未显示为链接,但在更下方显示良好

jquery - 为什么通过 npm 安装语义 UI 会错过 jQuery 并向其抛出引用错误?

node.js - 如何使用 Electron 生成器将 v8 快照打包到 exe 中?

javascript - 如果条件显示警报,即使条件为假