I'm using CRA and running an express app but when I run the express app localhost:8080 to render my index.html file it never runs app.get("*"). It seems to be hitting the use static and loading the html from there.
Any ideas on what this might be happening ?
server/index.js
const express = require("express");
const path = require("path");
const PORT = process.env.PORT || "8080";
const app = express();
const indexPath = path.join(__dirname, "../build/index.html");
app.use(express.static(path.resolve(__dirname, "../build")));
app.get("/test", (req, res) => {
res.json({ message: "welcome to backend" });
});
app.get("*", (req, res) => {
console.log("sending index.html");
res.sendFile(indexPath);
});
app.listen(PORT, () => console.log(`listing on port ${PORT}`));
My folder structure is.
CodePudding user response:
If this:
app.use(express.static(path.resolve(__dirname, "../build")));
finds a match for the incoming request in your build directory, then it will handle the request and the routes you have that follow will never get a chance to serve the incoming request. That's how express.static()
works. If you have a route that you don't want express.static()
to match, then make sure that there is no file that matches the path of the incoming route in your static directory structure.
In the particular case you mention, if express.static()
sees a request for /
, then it will look for index.html
in the directory you gave express.static()
and if it finds that there, it will just serve it and finish the request.
You can control whether it matches /
to index.html
in a couple ways. First, if there is no index.html
in that build
directory, then express.static()
won't find it. Or, second, you can pass a configuration option {index: false}
to express.static()
to tell it you don't want it to serve index.html
for /
like this:
app.use(express.static(path.resolve(__dirname, "../build"), {index: false}));
In your specific case, it's unclear why any of this is a problem because your route:
const indexPath = path.join(__dirname, "../build/index.html");
app.get("*", (req, res) => {
console.log("sending index.html");
res.sendFile(indexPath);
});
Just sends the same index.html
file either way.
FYI, it's generally not considered wise to send index.html
for any url request that is otherwise matched as you are going with app.get('*', ...)
because it is more difficult for search engines and other robotic crawlers to tell which pages actually exist on your site and which don't. You probably also don't want users bookmarking a non-existent URL that just happens to work as that page may change into some other real content or some other purpose some time in the future.