Vishnu Sureshkumar
Vishnu Sureshkumar

Reputation: 2316

Node JS Express all requests showing 404

All requests are showing GET / 404 8.128 ms-13 in console.

I have posted the code below, there is no error in the code. I can run other NodeJS applications. But this is showing 404 in console. It is not even showing the fav icon. It worked once showing Cannot GET / error and the fav icon was visible at that time.

'use strict';
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var favicon = require('serve-favicon');
var logger = require('morgan');
var port = process.env.PORT || 8001;
var four0four = require('./utils/404')();
var environment = process.env.NODE_ENV;
app.use(favicon(__dirname + '/favicon.ico'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(logger('dev'));
app.use('/api', require('./routes'));
console.log('About to crank up node');
console.log('PORT=' + port);
console.log('NODE_ENV=' + environment);
switch (environment){        
default:
    console.log('** DEV **');
    app.use(express.static('./src/client/'));
    app.use(express.static('./'));
    app.use(express.static('./tmp'));
    app.use('/app/*', function(req, res, next) {
        four0four.send404(req, res);
    });
    app.use('/*', express.static('./src/client/index.html'));
    break;
}
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());
});

Upvotes: 1

Views: 1899

Answers (1)

Tan Nguyen
Tan Nguyen

Reputation: 3354

According to http://expressjs.com/starter/static-files.html I think that your route here app.use('/*', express.static('./src/client/index.html')); will use ./src/client/index.html as the base path and append whatever you provide to find a file. For example

/some-file will look for ./src/client/index.html/some-file which is obviously not existed

In case you want to understand it more, the static middleware use https://github.com/pillarjs/send internally to stream file

So you can do this app.use('/*', express.static('./src/client'));

It will, by default, set / to src/client/index.html, you can change that behaviour by setting index option as specified here https://github.com/expressjs/serve-static

If you want to redirect /* to ./src/client/index.html do this

// first set the static middleware
app.use('/public', express.static('./src/client'));
// then use redirect
app.get('/*', function(req, res, next){
  res.redirect('/public/index.html');
});

This setup will redirect everything to public/index.html. If you want to add APIs or other routes, put it before the app.get('/*')

Upvotes: 1

Related Questions