Express fallback route also used for static files

Viewed 3874

I am trying to create an express application that works with React and React-router on the front end. So I'm loading the index.html file and let react router handle the rest of the routing. But when refreshing on a page with a react router url that doesn't have an express route I obviously get the message {cannot GET .....}. So i added a fallback route after all my routes to always return index.html when there is no route.

So now I have routes to "/api/...", "/" and "*", I am also serving static files from "/public/build" and "/app/src/static/". When calling the "/" everything works great, when calling the "*" the index.html gets loaded, but the index.js and styles.css files are both loaded with the content from index.html. So my browser gets a styles.css file with a bunch of html in it whereas when using the "/" route the .js and .css files get loaded correctly.

So navigating to "/" loads the index page correctly with all the static files. I can then use my react-router-dom NavLink to navigate to difirent views without making a request back to the server. But when i try to load any react-router-dom page directly I get my index.html but my index.js has the same contents as index.html, same for styles.css

My code:

const app = express();

app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());

passportConfig(passport);
app.use(passport.initialize());
app.use(passport.session());

app.use('/api/user', userRoutes);
app.use('/api', championRoutes);

app.use('/public/build', express.static(__dirname + '/public/ReactApp/build'));
app.use("/app/src/static/image", express.static(__dirname + '/public/ReactApp/src/static/image'));
app.use("/app/src/static/style", express.static(__dirname + '/public/ReactApp/src/static/style'));

app.get('/', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'index.html'));
});

app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, '..', 'index.html'));
});

app.listen(8080, () => {
   console.log('started on port 8080');
});

The userRoutes and championRoutes variables both contain an express.Router object that has a few routes set.

Edit:

<!DOCTYPE html>
<html>
    <head>
        <title>Page Title</title>
        <link href="app/src/static/style/styles.css" rel="stylesheet" />
        <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
    </head>
    <body>
        <div id="app"></div>

        <script
                src="https://code.jquery.com/jquery-3.2.1.min.js"
                integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
                crossorigin="anonymous"></script>
        <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
        <script src="public/build/index.js"></script>
    </body>
</html>
1 Answers
Related