Sparkles the unicorn
Sparkles the unicorn

Reputation: 23

Express.js: Specifying a root route breaks static file resolvement

I'm trying to make an express.js / react.js app but I'm running into a couple of issues I find no answer for.

I set up a base directory that holds the express server, and a subdirectory called client which holds my react application.

When I use the default, as used in many examples:

app.get( express.static( path.join( __dirname, 'client/build' ) ) );

The app works and loads every file correctly.

But I would prefer to not have the app run at the root of my server but instead in a subdirectory. e.g. /app.

So, according to what I've found. All I need to change in my server.js is the following:

app.get( '/app', express.static( /*...*/ ) );

I also modified my react app to change its links to include /app. However, adding a root breaks everything. While the default index.html does load. None of the other files get loaded. When trying to request the link to one of the files. I get Cannot GET /app/favicon.ico (per example), The same message I get when requesting a non existing path.

Without any success I have also tried:

router.get( express.static( /*...*/ ) );
app.get( '/app', router );

and

app.route( '/app' ).get( express.static( /*...*/ ) );

What am I missing?

Upvotes: 0

Views: 92

Answers (1)

Sparkles the unicorn
Sparkles the unicorn

Reputation: 23

As it turns out. You would have to use express.use instead of express.get. At first I didn't understand the difference but after changing all calls to .use. everything worked.

Working code:

app.use( '/app', express.static( /*...*/ ) );

as well as

const approuter = express.Router();
approuter.use( express.static( /*...*/ ) );
app.use( '/app', approuter );

Upvotes: 1

Related Questions