kamalakshi hegde
kamalakshi hegde

Reputation: 101

responding with index.html in express and react

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

Upvotes: 4

Views: 5293

Answers (2)

ocespedes
ocespedes

Reputation: 1303

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.

Upvotes: 1

mikkelrd
mikkelrd

Reputation: 413

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

Upvotes: 2

Related Questions