Search code examples
node.jsreactjsexpressreact-navigationproduction

Problem refresh pages nodejs cannot /get error


I have built a website and when I am on the home page and refresh it is fine but when I navigate to other pages its fine too but when I refresh on these other pages

Cannot GET /otherpage

I am using react-navigation and if I hyperlinked it I think it may not have worked otherwise either.


require('rootpath')();
const express = require('express');
const app = express();
///
///
app.use('/accounts', require('./accounts/accounts.controller'));

if(process.env.NODE_ENV === 'production'){
 
  app.use(express.static('build'));

 

  }
server.js
build

file directory

How do I go about fixing this problem?


Solution

  • // Serve the static files from the React app
    app.use(express.static(path.join(__dirname, 'client/build')));
    
    // An api endpoint that returns a short list of items
    app.get('/api/getList', (req,res) => {
        var list = ["item1", "item2", "item3"];
        res.json(list);
        console.log('Sent list of items');
    });
    
    // Handles any requests that don't match the ones above
    app.get('*', (req,res) =>{
        res.sendFile(path.join(__dirname+'/client/build/index.html'));
    });
    

    Follow this tutorial on further explanation: https://dev.to/nburgess/creating-a-react-app-with-react-router-and-an-express-backend-33l3