Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

javascript - Node + Express with static HTML. How to route all requests to index.html?

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

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.

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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)
})

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...