问题
My issue here is incredibly similar if not exactly the same as the one outlined in this issue. Unfortunately, I haven't been able to resolve it using the strategy it provides. So here are my own details:
I am using Create React App, React Router 4, Express, and Heroku and have followed the instructions here with regards to setting up a server with CRA.
Locally, I am able to access routes such as myapp/about
, yet after building and pushing to heroku, these 404.
I can navigate to this route via the UI (i.e. by clicking on a menu item that pushes a route onto history
), yet am unable to navigate to this route using only my browser's address bar. Furthermore, when I navigate using the UI, I'm not seeing any network activity related to the route such as an /about
request. Yet when I change the address bar and hit enter, this yields a network request to said route.
Here are some select snippets from my code:
app.js
<Switch>
<Route exact path="/about" component={About} />
<Route path="/"
render={props => <coolListContainer {...props}/>} />
</Switch>
server.js
if (process.env.NODE_ENV === 'production') {
app.use(express.static('client/build'));
}
//...what some of my api routes look like:
app.route('/api/verify')
.post( async (req, res) => {
try {
await db.verifyCode(req.body)
res.json('success')
} catch (err) {
res.json(err);
}
}
});
My directory structure as provided by full-stack-react`'s express demo.
└── myapp
├── Procfile
├── README.md
├── client
│ ├── build
│ │ ├── asset-manifest.json
│ │ ├── index.html
│ │ └── static
│ │ ├── css
│ │ │ ├── main.e8c50ca0.css
│ │ │ └── main.e8c50ca0.css.map
│ │ └── js
│ │ ├── main.24fe0ebe.js
│ │ └── main.24fe0ebe.js.map
│ ├── package.json
│ ├── public
│ │ └── index.html
│ ├── src
│ │ ├── About.js
│ │ └── index.js
│ └── styles
│ └── about..css
├── package.json
├── server.js
└── static.json
Per answer given to this post, I've also plopped a static.json
file into the root directory.
static.json
{
"root": "client/build/",
"clean_urls": false,
"routes": {
"/**": "index.html"
}
}
The above configuration gives me 404s on any route.
回答1:
Alrighty, I figured this out.
All I needed was to ensure that any request not relevant for my internal API, such as a GET
request via the address bar, is routed directly to my index.html
file which handles the dynamic routing via React Router. Seems obvious enough now.
Here is the final route in my app.js
:
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, '/client/build/index.html'));
});
来源:https://stackoverflow.com/questions/44723509/react-routing-works-in-locally-but-not-heroku