Refreshing React with Express server

≯℡__Kan透↙ 提交于 2020-01-06 08:10:13

问题


I have looked through the questions and can't seem to find the answer. There are similar ones but none that have helped.

Here is the deal. I am trying to refresh my React page on any page but home i.e. https://amazingdomain/nextpage

I know, if I am on this page and I refresh I will get the Express 404 because it doesn't know what to send. My Server is hosted on AWS as an EC2 instance and my Frontend is hosted on a popular hosting site. Everything works fine until I try to refresh on a page other than home. I am at a loss here. I have search and can't find my answer.

My React Router looks like:

      render() {
    return (
        <Router>
          <div className="App">
            <Switch>
              <Route exact path="/" component={Homepage} />
              <Route exact path="/firstPage" component={FirstPage} />
              <Route exact path="/secondPage" component={SecondPage} />
              <Route exact path="/thirdPage" component={ThirdPage} />
              <Route path='/*' exact={true} component={Page404} />
            </Switch>
          </div>  
        </Router>

    );
  }
}

My server looks like:

const express = require("express");
const cors = require('cors');
const bodyParser = require('body-parser');
const nodemailer = require('nodemailer');

const config = require('./config.js');

const app = express();

app.use(cors());
app.use(express.json());

app.use((req, res, next) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
});


//Here is my attempt to get the page to refresh
app.get('*', (req, res) =>{
    res.sendFile(path.join(__dirname + '/public/index.html'));
});

app.listen(port, () => {
    console.log(`Server Running on Port: ${port}`);
});

I know there is a hashrouter and I would like to avoid using it. I know there is browserrouter as well. I have tried but I still get the 404 error.

I want to be able to go to https://amazingdomain/firstpage hit f5 and go right back to that same page in production. Any help would be appreciated!

来源:https://stackoverflow.com/questions/58124847/refreshing-react-with-express-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!