xtabbas
xtabbas

Reputation: 647

Express server with React front end routing without server side rendering

This is my express server setting

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var mongoose = require('mongoose');

var app = express();

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


require('./api/accounts/signin')(app);
....

mongoose.connect(process.env.MONGO_URI);
mongoose.connection.on('error', function() {
    console.info('Error: Could not connect to MongoDB. Did you forget to run `mongod`?');
});

app.set('super-secret', process.env.APP_SECRET)

module.exports = app;

Now when i start my application at localhost:3000/ it works fine with all the routes working but when i try to go on localhost:3000/login or some other route directly i get a Cannot GET /login error...

I dont want to use server side rendering with a react middleware (which i have used before) just now so is there anyway to make it work?

app.get('/*/*', function(req, res) {
  res.sendFile(path.join( __dirname, 'public/index.html'))
})



<!doctype html>
<html>
  <head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>
    <title>Doyouthink?</title>
  </head>
  <body>
    <div id="root"></div>
    <script src="js/common.bundle.js"></script>
    <script src="js/polyfill.bundle.js"></script>
    <script src="js/vendor.bundle.js"></script>
  </body>

</html>

Upvotes: 1

Views: 739

Answers (1)

Paul S
Paul S

Reputation: 36787

You just need to match all routes and serve them the base html page which includes your bundle. React Router will then examine and URL and render the appropriate components.

app.get("/", handleRender);
app.get("*", handleRender);

function handleRender(req, res){
  res.sendFile(__dirname + '/index.html');
}

Upvotes: 1

Related Questions