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

后端 未结 6 1602
迷失自我
迷失自我 2020-12-09 10:31

I have installed http-server globally.

I launch it from myDir on localhost port 8080. In myDir I have index.html

6条回答
  •  孤城傲影
    2020-12-09 11:07

    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.

提交回复
热议问题