Express server serves up react build files without needing app.get('/')

Viewed 48

so my node.js express server works great with my react frontend BUT I'm confused why it works...

This is my server.js file

var express = require('express');
var app = express();

var path = require('path');

var server = require('http').Server(app);
var io = require('socket.io')(server);


// Set up the path for the quickstart.
var quickstartPath = path.join(__dirname, './quickstart/public');
app.use('/quickstart', express.static(quickstartPath));


app.use(express.static(path.join(__dirname, 'build')));


server.listen(process.env.PORT || 4000);
console.log('server running');


//WHY IS THE App.get(/) NOT NECESSARY?!
app.get('/', function(req, res){
    res.sendFile(path.join(__dirname, 'build', 'index.html'));
});


I did npm run build on my react files, and then moved that build folder/directory into same directory as my server.js file.

I node server.js and by going to localhost: 4000, the entire thing works and runs great!

But if I delete app.get('/') it still works great.

Only if I delete app.use(express.static(path.join(__dirname, 'build'))) does the index.html (located in ./build/index.html) not get loaded.

I thought by typing in localhost:4000 it would make a get request to \ and from there send the index.html file, but app.get is not being called?

I'm just trying to understand why, even though everything works great.

Thanks!

1 Answers

It is working because express.static() by default sends the index file of the specified directory, in your case, it is build/index.html.

Check the documentation here,

https://expressjs.com/en/4x/api.html#express.static

express.static(root, [options])

You can disable it by setting the index property of the options to false

app.use(express.static(path.join(__dirname, 'build'), { index: false }));
Related