Javascript 带有静态 HTML 的 Node + Express。如何将所有请求路由到 index.html?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26349497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Node + Express with static HTML. How to route all requests to index.html?
提问by JPollock
I am working on a single page web app using Node + Express and Handlebars for templating. Everything currently works well from index.html, which is served from a pretty standard server.js file:
我正在使用 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);
});
This works perfectly when loading from http://localhost:10001/. My issue is that I'm using push states in the app, so the browser may show a URL like http://localhost:10001/foo/barand then if I refresh the page, I get the error Cannot GET /foo/barsince there is no route for this.
从http://localhost:10001/. 我的问题是我在应用程序中使用推送状态,所以浏览器可能会显示一个 URL http://localhost:10001/foo/bar,然后如果我刷新页面,我会收到错误消息,Cannot GET /foo/bar因为没有路由。
So my question, and pardon my incredible noobishness when it comes to Node, can I make it so all requests route to index.html? The JavaScript in my app can handle showing the right content based on URL params on page load. I don't want to define custom routes as the number would be large, and the paths for them can change dynamically.
所以我的问题,请原谅我对 Node 的难以置信的笨拙,我可以让所有请求都路由到 index.html 吗?我的应用程序中的 JavaScript 可以根据页面加载时的 URL 参数处理显示正确的内容。我不想定义自定义路由,因为数量会很大,而且它们的路径可以动态更改。
回答by cdock
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)
})
回答by Nick Tomlin
This pattern will serve static assets before hitting the catch-all route that serves up your front-end application. To register any additional routes, just add them above the catch-all route.
此模式将在命中为前端应用程序提供服务的全能路由之前提供静态资产。要注册任何其他路由,只需将它们添加到全部路由之上。
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);
});
回答by Deepak
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));
回答by ZitRo
This short thing works well:
这个简短的东西很好用:
import express from "express";
const app = express(),
staticServe = express.static(`${ __dirname }/public`);
app.use("/", staticServe);
app.use("*", staticServe);
Just make sure that all URLs from your HTML/JS files are absolute now, as all resources that do not exist will return index.htmlfile.
现在只需确保 HTML/JS 文件中的所有 URL 都是绝对的,因为所有不存在的资源都将返回index.html文件。
Express v 4.15.2
Express v 4.15.2
回答by vodolaz095
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);
});

