Lc0rE
Lc0rE

Reputation: 2346

Express: serve static files on subroute

I'm trying to get routing work using Express and create-react-app.

My goal is to address the user to the homepage of the application when the URL is / and to the login page when the URL matches /login.

In my server.js I have two routes defined:

var mainRoutes = require("./routes/mainRoutes");
var apiRoutes = require("./routes/apiRoutes");

[...]

app.use("/", mainRoutes);
app.use("/api", apiRoutes);

While apiRoutes contains all the api routing definitions, mainRoutes is responsible for the main navigation (at least this was the idea):

var express = require("express");
var path = require("path");

let router = express.Router();

router.route("/").get((req, res, next) => {
  res.sendFile("index.html", { root: "./client/build/" });
});

router.route("/login").get((req, res, next) => {
  res.send("This is the login page");
});

module.exports = router;

Somewhere I read about serving the static asset generated by the building process of create-react-app so I added:

// Priority serve any static files.
app.use(express.static(path.join(__dirname, "client/build")));

// All remaining requests return the React app, so it can handle routing.
app.get("*", function(req, res) {
  res.sendFile(path.join(__dirname + "/client/build/index.html"));
});

Adding these lines, I successfully see my index.html but I can't visit both /login and /apisubroutes since it redirect me on the main page (index.html) each time.

It's like I need to serve the static files on my subroute mainRoutes but I don't have an idea on how to do that.

How can I make this work?

Upvotes: 2

Views: 726

Answers (2)

Koray Gocmen
Koray Gocmen

Reputation: 715

app.get('*') would match every single route that you have.

You should do something like this:

var mainRoutes = require("./routes/mainRoutes");
var apiRoutes = require("./routes/apiRoutes");

[...]

app.use(express.static(path.join(__dirname, "client/build")));

app.use("/", mainRoutes);
app.use("/api", apiRoutes);

// If the app reaches this point, it means that 
// the path did not match any of the ones above
app.use(function(req, res, next){
  // redirect the user to where we serve the index.html
  res.redirect('/');
});

Upvotes: 1

Evil Dr. PorkChop
Evil Dr. PorkChop

Reputation: 379

create-react-app I believe handles routing different, you cannot hook up the browser's route to the route you want to serve because you're running a single page application", unless you do universal routing with server and the js bundle

Upvotes: 0

Related Questions