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

Pic*_*cci 11 httpserver node.js

我已在http-server全球安装.

我在localhost端口8080上从myDir启动它.在myDir中我有index.html.

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

如果我请求虽然http://localhost:8080/anything我没有从服务器得到任何响应.

相反,我想要的是我的服务器总是使用index.html响应任何到达端口8080上的localhost的http请求.

这可能吗.

提前致谢

Far*_*rov 10

按照文档中的说明使用。

http-server --port 8080 -P http://localhost:8080?
Run Code Online (Sandbox Code Playgroud)

请注意?代理 URL 末尾的 。

  • 在 mac zsh 上 `http-server --port 8080 -P "http://localhost:8080?"` (3认同)
  • 这位就干了这事!这个“?”很重要。 (2认同)

Jai*_*mez 6

使用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);
Run Code Online (Sandbox Code Playgroud)

index.html如果找不到所请求的文件,此实现将始终响应,并且它几乎与使用时一样简单http-server,缺少此选项.


Dra*_*SAN 5

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

http-server -P http://localhost:8080/
Run Code Online (Sandbox Code Playgroud)

请注意,包括 404 在内的任何错误都将重定向到您的索引,而不仅仅是缺少路径。

  • 我不知道 `http-server`,但由于任何错误都被重定向到索引,我假设你陷入了一个循环,直到客户端放弃。我个人会像@rsp 那样做,用 express 编写你自己的小服务器,它也很容易和快速。 (4认同)

Gab*_*iel 5

为了实现您的要求,我建议您使用live-server而不是http-server.

live-server --port=8080 --entry-file=./index.html
Run Code Online (Sandbox Code Playgroud)

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

编辑:实时服务器不适用于生产.例如,没有gzip压缩

编辑2:http-server的维护者在此评论中明确表示从不,http-server会考虑SPA用例

编辑3:发球似乎也是一个不错的选择