4

I have an express app where inside it has a create-react-app. when the user goes to root url I want to show the index.html present in create-react-app public folder. Here is my code for index.js in express app

const express = require("express");
const app = express();

app.get('/',function(req,res){


});

const PORT = process.env.PORT || 5000;
app.listen(PORT);

Here is my project directory

2 Answers 2

2

You need this line: app.use(express.static('public')). See here: https://expressjs.com/en/starter/static-files.html

Sign up to request clarification or add additional context in comments.

5 Comments

thats it? where should I add it
and how to get the path for the index.html
for now, just add it in place of your current app.get block. that should be all you need to serve index.html, because that basically tells your express app "when there is a get request to the base url, go ahead and expose this directory, and by default respond with the contents of an index.html file if present"
I want to use res.sendFile() method inside app.get('/')
that's fine. but the recommended way in the express docs is express.static, as shown in the link in my answer
1

If you want to use the sendFile() you can do something like this:

const router = express.Router();
router.get('/', (req, res) => {
    res.sendfile(path.join(__dirname, './client/public', 'index.html'));
});
app.use('/', router);

I'm using the path because depending how you start your app it might break with just the relative path.

4 Comments

Im getting this error : Error: ENOENT: no such file or directory, stat '/Users/sriram/Desktop/public/index.html'
Yes I will update the answer it is how the path is used, given your project structure, see the updated answer now
Yes this is working my title got changed to React App, but i didnt get the body of it , is it because of bundle.js or something related . Im using create-react-app by the way inside codit(express app)
As I can see from your folder structure picture you haven't built your app, make sure to run npm run build in your React app

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.