skip to Main Content

My React App runs perfectly fine when I run index.js. However, now I’m trying to move it to an Express server and when I refresh the page, I see the app run for about .5 seconds before it disappears to a white screen. I’ve taken out code, moved it all around, and I don’t know how to fix this issue.

I added another div in index.html (just saying "hello") and that stays, while my div "root" disappears.

Does anyone have any ideas?

This is server.js

process.env.NODE_ENV = 'development';
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const bodyParser = require('body-parser');
const path = require('path');

// create a new instance of Express application
const app = express();

// add middleware to parse incoming requests
app.use(cors({ origin: true, credentials: true }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

const port = process.env.PORT || 3000;

// define the API routes for your application
const router = express.Router();

router.get('/', function (req, res) {
  res.json({ message: 'API initialized' });
});

// other routes will be defined here
//app.use('/api/items', items);
app.use('/api', router);

// connect to MongoDB database using Mongoose
const conn_str = 'mongodb+srv://ashley:<password>@cluster0.vifnths.mongodb.net/?retryWrites=true&w=majority';

console.log(__dirname);

// serve static assets in production
app.use(express.static('build'));

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

mongoose.set('strictQuery', false);
mongoose.connect(conn_str, {
    useUnifiedTopology: true,
    useNewUrlParser: true,
})
.then(() => {
    app.listen(port)
    console.log('MongoDB Connection Succeeded...')
})
.catch(err => {
    console.log('Error in DB Connection ${err}');
});

I’ve taken out code and moved it all around. I can’t seem to fix the problem, despite knowing what it probably is.

2

Answers


  1. Chosen as BEST ANSWER

    I ended up figuring out the answer! I was missing these two lines:

    const items = require('./routes/api/items');
    
    app.use('/api/items', items);
    

    Basically I was calling items later in my code and I guess it was just not loading because I had no items to call from.


  2. The problem seems to be in this bit of code:

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

    It serves index.html as a response to all requests. However, you do not only need to serve index.html, but other assets as well (such as the JavaScript bundle, which contains your actual React app code).

    So, try removing that route, because this middleware already covers this functionality:

    app.use(express.static('build'));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search