ctlkkc
ctlkkc

Reputation: 57

nodejs express client Cannot GET /xxx.html before accessing main

I have the following server side code:

var app = express();
app.get('/', function (req, res) {
    res.redirect('/main');
});
app.get('/main', function (req, res) {
    var d = new Date();
    res.sendFile(path.join(__dirname + '/main.html'));
    Info(req.ip + ' - Session to main.html built successfully! ');
    app.use(express.static(__dirname));
});

Also there are some other html files in the same directory, e.g. xxx.html. I found the following behavior that confuses, if I build a new session, try to access localhost:7778/xxx.html, the client cannot get: Cannot GET /xxx.html:

Failed to load resource: the server responded with a status of 404 (Not Found)

On the other hand, after accessed localhost:7778/, and then try to access localhost:7778/xxx.html, will succeed.

Can anyone explain the behavior? Can I set the localhost/xxx.html be able to directly accessed?

Thanks a lot!

Upvotes: 0

Views: 159

Answers (1)

shaochuancs
shaochuancs

Reputation: 16226

You need to move app.use(express.static(__dirname)); outside of the app.get('/main', ...) handler:

var app = express();
app.get('/', function (req, res) {
    res.redirect('/main');
});
app.get('/main', function (req, res) {
    var d = new Date();
    res.sendFile(path.join(__dirname + '/main.html'));
    Info(req.ip + ' - Session to main.html built successfully! ');
});
app.use(express.static(__dirname));

According to Express document:

app.use([path,] callback [, callback...])

Mounts the specified middleware function or functions at the specified path

The specified middleware (express.static) should be declared as itself, and be executed once the server is started. It should not be executed as part of logic in GET /main's handler.

Upvotes: 1

Related Questions