node http-server to respond with index.html to any request

蹲街弑〆低调 提交于 2019-11-28 23:41:53

To achieve what you are asking for, I recommend you live-server instead of http-server.

live-server --port=8080 --entry-file=./index.html

live-server is also providing a hot-reload but it was not one of your request

Edit: live-server is not designed to be used in production. No gzip compression for example

Edit 2: The maintainer of http-server clearly said in this comment that never, http-server will consider the SPA use-cases

Edit 3: serve seems to be a good option too

Simple and straight-forward example using Express 4.x:

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

var path = __dirname + '/public';
var port = 8080;

app.use(express.static(path));
app.get('*', function(req, res) {
    res.sendFile(path + '/index.html');
});
app.listen(port);

This implementation will always respond with index.html if the requested file is not found, and it's almost as simple as using http-server, which lacks this option.

Yes there is, with the -P/--proxy option:

http-server -P http://localhost:8080/

Note that any error, 404 included, will redirect to your index, not just missing path.

Sometimes for specific cases like this one, it's easy enough to write your own server:

'use strict';
var host = '127.0.0.1', port = 3333;
var path = require('path');
var app = require('express')();
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
app.listen(port, () => console.log(`Listening on http://${host}:${port}/`));

But keep in mind that if every path returns index.html then in the index.html you cannot reference anything like images, style sheets or client side JavaScript files. Not only with the code shown above but with any solution that sends the same response (index.html) to every request.

You may need to make some exceptions and it's not hard with Express:

'use strict';
var host = '127.0.0.1', port = 3333;
var path = require('path');
var app = require('express')();
app.get('/x.png', (req, res) => res.sendFile(path.join(__dirname, 'x.png')));
app.get('*', (req, res) => res.sendFile(path.join(__dirname, 'index.html')));
app.listen(port, () => console.log(`Listening on http://${host}:${port}/`));

Just keep in mind that the exceptions have to go to the top because the first matching route will be used for a given request.

Of course you need to save this code e.g. to app.js, install Express:

npm install express

and start it with:

node app.js

It's more complicated than using a ready solution (though, as you can see, not that complicated either) but you have much more flexibility in how exactly you want it to behave. It's also easy to add logging etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!