Get backend server.js file to recognize React views

When I look up how to connect your React frontend to an Express backend I keep getting some combination of this middleware:

app.use(express.static(path.join(__dirname, 'public')));

And then maybe a catch-all route like this:

app.get('*', (req, res) => {

    res.sendFile(path.join(__dirname + '/public/index.html'))


The problem is it still doesn’t read my React frontend. When I have them running on different ports and use Concurrently to get them both running at the same time it works fine. I’m starting to think it’s in my file structure. I have the frontend in its own folder called ‘/frontend’. The public folder is in ‘/frontend/public’. The backend is in server.js which is on the same level as the frontend folder.

Most tutorials I look up just kind of dive in to coding that middleware without actually explaining what the file structure must be for it to work. I was wondering if someone could provide a discussion on how Express knows where to look for that public folder. In my Console I’m getting this, if that helps:

%PUBLIC_URL%/manifest.json:1 Failed to load resource: the server responded with a status of 400 (Bad Request)

1 Like

Do you have it on Glitch? Might be easier to check. If you don’t maybe give it a try, should be straight forward to get it there.

Also I’d redirect the middleware to ‘src’ instead of ‘public’ but again, it’s easier by testing.

I’ve it running using this set up:

const express = require('express');
const path = require('path');
const app = express();
app.use(express.static(path.join(__dirname, 'build')));
app.get('/', function(req, res) {
  res.sendFile(path.join(__dirname, 'build', 'index.html'));

And if you look up in the index.html under the build folder, it should have paths starting with /static.

Yet if it does not run, check you don’t have a homepage in the package.json. I believe that might interfere.

I could upload the complete example to Glitch if you think it’s helpful.

I will look into Glitch. By Homepage, are you saying it should or shouldn’t have a homepage listen in package.json?

When there is a homepage for github pages, that’s taken into account when rendering the build files. So the paths are pretty weird in that case. I’ve just removed the ‘homepage’ (if there is one) and run npm run build

I’ve set up a project I had so you can check things out;

If you run node server.js it runs the server it launches the site.