带有静态 HTML 的 Node + Express.如何将所有请求路由到 index.html? [英] Node + Express with static HTML. How to route all requests to index.html?

查看:21
本文介绍了带有静态 HTML 的 Node + Express.如何将所有请求路由到 index.html?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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 因为没有这个路由.

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/bar and then if I refresh the page, I get the error Cannot GET /foo/bar since there is no route for this.

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

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.

推荐答案

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)
})

这篇关于带有静态 HTML 的 Node + Express.如何将所有请求路由到 index.html?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆