【问题标题】:Node + Express with static HTML. How to route all requests to index.html?带有静态 HTML 的 Node + Express。如何将所有请求路由到 index.html?
【发布时间】:2014-12-08 13:54:03
【问题描述】:

我正在开发一个使用 Node + Express 和 Handlebars 进行模板的单页 Web 应用程序。 index.html 目前一切正常,它由一个非常标准的 server.js 文件提供:

var express = require('express');

var server = express();
server.use(express.static(__dirname + '/public'));

var port = 10001;
server.listen(port, function() {
    console.log('server listening on port ' + port);
});

这在从http://localhost:10001/ 加载时非常有效。我的问题是我在应用程序中使用推送状态,因此浏览器可能会显示类似http://localhost:10001/foo/bar 的 URL,然后如果我刷新页面,我会收到错误 Cannot GET /foo/bar,因为没有路由。

所以我的问题,请原谅我对 Node 的难以置信的愚蠢,我可以让所有请求都路由到 index.html 吗?我的应用程序中的 JavaScript 可以根据页面加载时的 URL 参数处理显示正确的内容。我不想定义自定义路由,因为数量会很大,并且它们的路径可以动态更改。

【问题讨论】:

    标签: javascript node.js express


    【解决方案1】:
    const express = require('express')
    const server = express()
    
    /* route requests for static files to appropriate directory */
    server.use('/public', express.static(__dirname + '/static-files-dir'))
    
    /* other routes defined before catch-all */
    server.get('/some-route', (req, res) => {
      res.send('ok')
    })
    
    /* final catch-all route to index.html defined last */
    server.get('/*', (req, res) => {
      res.sendFile(__dirname + '/index.html');
    })
    
    const port = 8000;
    server.listen(port, function() {
      console.log('server listening on port ' + port)
    })
    

    【讨论】:

    • 正如其他答案中所指出的,注意包罗万象的路由应该在静态中间件和其他 get 路由之后。
    • public in => "server.use('/public', express.static(__dirname + '/public')); 有什么用.可以在以后的步骤中使用别名 "__dirname + '/public'" ,同时为具有指定路由名称的单个文件提供服务吗?
    【解决方案2】:

    此模式将在到达为您的前端应用程序提供服务的包罗万象的路线之前提供静态资产。要注册任何其他路线,只需将它们添加到 catch-all 路线上方即可。

    var express = require('express');
    var server = express();
    
    // middleware
    server.use(express.static(__dirname + '/public'));
    
    // routes
    server.use('*', function (req, res) {
      // serve file
    });
    
    var port = 10001;
    server.listen(port, function() {
      console.log('server listening on port ' + port);
    });
    

    【讨论】:

    • 嘿,只是想指出您正在导入 static 但从未真正使用它,因为您这样做了 express.static
    • @kemicofa 很棒的收获!固定!
    【解决方案3】:
    var app = express();
    
    var options = {
      dotfiles: 'ignore',
      etag: true,
      extensions: ['htm', 'html'],
      index: 'index.html',
      lastModified: true,
      maxAge: '1d',
      setHeaders: function (res, path, stat) {
        res.set('x-timestamp', Date.now());
        res.header('Cache-Control', 'public, max-age=1d');
      }
    };
    
    app.use(compression());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(methodOverride());
    
    app.use('/', express.static(__dirname + '/public', options));
    app.use('*', express.static(__dirname + '/public', options));
    

    【讨论】:

      【解决方案4】:

      这个简短的东西效果很好:

      import express from "express";
      
      const app = express(),
            staticServe = express.static(`${ __dirname }/public`);
      
      app.use("/", staticServe);
      app.use("*", staticServe);
      

      现在只需确保 HTML/JS 文件中的所有 URL 都是绝对的,因为所有不存在的资源都将返回 index.html 文件。

      Express v 4.15.2

      【讨论】:

        【解决方案5】:
        var express = require('express');
        
        var server = express();
        server.use(express.static(__dirname + '/public'));
        
        server.get('*', function(req, res){
          res.sendFile('index.html');
        });
        
        var port = 10001;
        server.listen(port, function() {
            console.log('server listening on port ' + port);
        });
        

        【讨论】:

        • 这适用于我所做的编辑,除了它还作用于我的 CSS 文件的 URL,因此它提供 index.html 而不是 CSS 文件。有没有办法只通过 mime 类型应用它(即,只在 html 上)。
        • @JPollock 在你的包罗万象的路线之前为公共文件注册中间件。这样,对 css/js 的请求将在您的索引路由之前被提取。
        猜你喜欢
        • 2016-07-23
        • 2021-10-29
        • 2018-04-03
        • 2013-08-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多