节点http-server用index.html响应任何请求

我已经在全球安装了http-server

我从本地端口8080 myDir启动它。在myDir我有index.html

如果我请求(从浏览器) http://localhost:8080/我得到index.html,这是好的。

如果我请求通过http://localhost:8080/anything我没有得到任何来自服务器的回应。

我想,相反,我的服务器总是以index.html响应任何http端口8080端口上的本地主机。

这可能吗。

提前致谢

是的,用-P / --proxy选项:

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

请注意,包含404的任何错误都将redirect到您的索引,而不仅仅是丢失的path。

有时对于像这样的特定情况,编写自己的服务器很简单:

 '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}/`)); 

但请记住,如果每个path都返回index.html那么在index.html您不能引用任何类似图像,样式表或客户端JavaScript文件。 不仅是上面显示的代码,而且还有任何解决scheme都会向每个请求发送相同的响应( index.html )。

您可能需要制定一些例外规定,但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}/`)); 

只要记住,例外必须到顶部,因为第一个匹配的路线将用于给定的请求。

当然你需要把这个代码保存到app.js ,安装Express:

 npm install express 

并开始:

 node app.js 

这比使用现成的解决scheme要复杂得多(不过,正如你所看到的,不是那么复杂),但是你有更多的灵活性来决定你的行为。 这也很容易添加日志等

为了达到你所要求的,我build议你使用live-server而不是http-server。

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

live-server也提供热重载,但这不是你的要求之一

使用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); 

如果没有find请求的文件,这个实现将总是以index.html作为响应,这与使用缺less这个选项的http-server一样简单。