简体   繁体   English

ExpressJs不提供index.html

[英]ExpressJs is not serving index.html

I have an Angular client application that runs entirely in the browser. 我有一个完全在浏览器中运行的Angular客户端应用程序。 I am trying to use expressjs to host it. 我正在尝试使用expressjs托管它。 I modeled the server code after the server.js in John Papa's MEAN Hot Towel application that he uses in his Pluralsight Gulp course. 我在John Papa在他的Pluralsight Gulp课程中使用的MEAN Hot Towel应用程序中的server.js建模了服务器代码。 This is my server code: 这是我的服务器代码:

var express = require('express');
var app = express();
var port = process.env.PORT || 7203;
var environment = process.env.NODE_ENV;

console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);

app.get('/ping', function(req, res) {
    console.log(req.body);
    res.send('pong');
});

console.log('** DEV **');
app.use(express.static('./src/app'));
app.use(express.static('./'));
app.use(express.static('./temp'));
app.use('/*', express.static('./src/index.html'));

app.listen(port, function() {
    console.log('Express server listening on port ' + port);
    console.log('env = ' + app.get('env') +
        '\n__dirname = ' + __dirname +
        '\nprocess.cwd = ' + process.cwd());
});

When I navigate to localhost:port/ping, I get pong back. 当我导航到localhost:port / ping时,我得到了pong。 When I navigate to localhost:port/ I get a 404 error. 当我导航到localhost:port /时,出现404错误。 Can someone tell me what I am doing wrong here? 有人可以告诉我我在做什么错吗?

As @tommyd456 stated in the comments above, you need to declare a route for '/', like so: 如上述注释中的@ tommyd456所示,您需要声明'/'的路由,如下所示:

app.get('/', function(req, res) {
    res.send('Hello!');
});

From the express documentation , it seems that express.static targets a folder . 从express 文档中 ,似乎express.static是针对文件夹的
So, replacing app.use('/*', express.static('./src/index.html')); 因此,替换app.use('/*', express.static('./src/index.html')); by app.use('/*', express.static('./src')); 通过app.use('/*', express.static('./src')); fix your problem and index.html will be served under 'localhost:port/' 解决您的问题,index.html将在“ localhost:port /”下提供

So after many hours of fiddling and reading I replaced this code: 因此,经过数小时的摆弄和阅读,我替换了以下代码:

app.use(express.static('./src/app'));
app.use(express.static('./'));
app.use(express.static('./temp'));
app.use('/*', express.static('./src/index.html'));

with this: 有了这个:

app.use(express.static(__dirname));
app.use(express.static(process.cwd()));

app.route('/*')
    .get(function(req, res) {
        res.sendFile(__dirname + '/index.html');
    });

and it appears to have solved the problem 看来已经解决了问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM