Skip to content Skip to sidebar Skip to footer

React Router Doesn't Work On Express Server

I am new to react, and I am trying to build a chat-app with it. I used react-router to load different components according to the url. In my react project foler (client/src/index.j

Solution 1:

React Router does all the routing in the browser, so you need to make sure that you send the index.html file to your users for every route.

This should be all you need:

app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.get('*', function(req, res) {
  res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});

Solution 2:

You must serve the static files and handle any request in your index.js:

const express = require('express');
const path = require('path');

const app = express();

// Serve the static files from the React app
app.use(express.static(path.join(__dirname, 'client/build')));

// Handles any requests that don't match the ones above
app.get('*', (req,res) =>{
    res.sendFile(path.join(__dirname+'/client/build/index.html'));
});

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

console.log('App is listening on port ' + port);

Solution 3:

* worked instead of using / in app.get() otherwise it'll always show cannot get. Thanks @basse

Solution 4:

Getting rid of this block helped me

app.use(function(req, res, next) {
  next(createError(404));
});

Solution 5:

app.get("/get/data/from/store", (req, res) => {
             your sql codes here
  });

// You must place all your above REST API Calls before the below codes. // Otherwise all urls '*' will be forwarded to index.html

// wildcard handles any requests that don't match the ones ABOVE

app.use(express.static(path.join(__dirname, '/build')))

    app.get('*', (req, res) => {
      res.sendFile(path.resolve(__dirname+'/build/','index.html'));
    });
    app.listen(port, () => {
      console.log("Server running on port ", port);
    });
    
    put the wildcard app.get('* call at the end. Just before the app.listen.

Post a Comment for "React Router Doesn't Work On Express Server"