Wednesday 28 November 2018

Express serving static files without actually making a call to 'res.sendFile(...)', help appreciated.

Hi, y'all, I've got a pretty standard express node / react app here but I'm getting some weird behavior.Like any typical setup, to serve static files I have,app.use(express.static(path.join(__dirname, "client/build")));...later in the file, we have,app.get("*", (req, res) => {console.log("hi");res.sendFile(path.join(__dirname + "/client/build/index.html"));});I would expect the request to reach that route, then serve the file. However, it looks like the file is served at the first line. I'm not sure what's happening, I haven't had this experience before when I've previously built react/express apps.I have a feeling it has something to do with the fact that when we pass the express.static( ) to the app.use( ), it's automatically serving the index.html...​I'll go ahead and post full code below.​const express = require("express");const app = express();const bodyParser = require("body-parser");const session = require("express-session");//pass session middleware to sesssion storeconst MongoDbSessionStore = require("connect-mongodb-session")(session);const userRoutes = require("./routes/user");const emailRoutes = require("./routes/email");const workoutRoutes = require("./routes/workout");const loginRoutes = require("./routes/login");const { mongoUri, sessionSecret } = require("./config/keys");const isAuth = require("./auth/isAuth");const path = require("path");// allow express to serve static content from react-build//init and configure storeconst store = new MongoDbSessionStore({uri: mongoUri,collection: "sessions"});const mongoose = require("mongoose");mongoose.connect(mongoUri,{ useNewUrlParser: true }).then(() => console.log("MongoDB connected")).catch(err => console.log(`There is an err:${err}`));//init session with store for the appapp.use(session({secret: sessionSecret,resave: false,saveUninitialized: false,store}));app.use(express.static(path.join(__dirname, "client/build")));app.use(bodyParser.json());app.use(bodyParser.urlencoded({ extended: false }));app.use("/user", userRoutes);app.use("/email", isAuth, emailRoutes);app.use("/login", loginRoutes);app.use("/workout", isAuth, workoutRoutes);// app.use(express.static(path.join(__dirname, "client/build")));// generic catch all routeapp.get("*", (req, res) => {console.log("Request never comes here lol wat??");res.sendFile(path.join(__dirname + "/client/build/index.html"));});//why are we hereapp.use((req, res) => {res.send("

Something went wrong

home");});const PORT = process.env.PORT || 9001;app.listen(PORT, () => console.log(`app starting on ${PORT}`));​Any help would be appreciated, thank you so much!

Submitted November 29, 2018 at 12:15AM by GGENYA

No comments:

Post a Comment