0

I'm fairly new to CRA, and normally I just use regular React with Webpack. I'm trying to serve my CRA just like I would any other React apps. My root directory file structure currently looks something like this:

controllers/
build/
app.js
package.json

Where "app.js" is my Node/Express server, build/ is the build folder for my CRA application (the index.hmtl, static directory, manifest, etc. are all here), and controllers/ is my router files. The router file I have to serve my react, called "staticController.js", is in the controllers/ directory and looks like this:

const express = require("express");
const path = require("path");
const router = express.Router();

router.get("/client/static/home", (req, res) => {
    res.sendFile(path.join(__dirname, ".." , "/build/index.html"));
})

module.exports = router;

I import this router module into app.js to use it, and run the router on port 3001. When I go to localhost:3001/client/static/home, I get a blank page and an error saying:

GET http://localhost:3001/static/css/1.1ee5c864.chunk.css net::ERR_ABORTED 404 (Not Found)

I'm not sure how to specifiy to CRA that the static directory and all associated build files should be under the "build/" directory. So instead, I move the static folder outside the build directory, into the root directory. The file structure looks like this now:

controllers/
build/
static/
app.js
package.json

When I try the route again, I still get the same error. Now I'm a bit confused as to how Node file structure works. If app.js is in the root directory, wouldn't localhost:3001/static/ just be my static/ folder? Why can't the CRA app find this folder?

2 Answers 2

1

use

express.static

to serve the build folder (or any static files)

e.g. : here i'm serving the build folder on the root path (assuming it's located on the same directory as the server file)

app.use('/', express.static('build'));
Sign up to request clarification or add additional context in comments.

Comments

0

I believe what you are looking for is static.

https://expressjs.com/en/4x/api.html#express.static

You need something like

var express = require('express');
var app = express();
app.use(express.static('static'));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.