简体   繁体   中英

How to make Express server use React routes?

Previous I had my server running on port 5000 and my react app running on port 3000. I would access it through port 3000 and it would do API calls to port 5000.

I have now added this so that the server will serve the react build: 在此处输入图像描述

But the issue I have now, is that all my routers on the app don't work. When I go to http://localhost:5000/ my homepage shows up fine, but if I go to http://localhost:5000/1 or whatever, it says it cannot get those pages.

What's meant to happen is that my router here kicks in and loads the correct components: 在此处输入图像描述

I'm new to the MERN stack and this is my first time trying to have the server send the build files. What should I search to solve this? How can I fix this? My guess is that I have to rewrite the app.get to send the correct files, but my build only has one file so IDK what to do. I'd rather not have to rewrite my whole server.

You have no .htaccess and no nginx and any other URL redirector here. You can handle it with express:

app.get('*', (req,res) =>{
  res.sendFile(path.join(__dirname+'../poll/build/index.html'));
});

After your express routes.

React route do routing on browser. but in here routing is done in server side. you should always return index.html in react application no mater which url you request.

if you want to work with both server side routing and browser routing, you may use HashRouting in react

https://reacttraining.com/react-router/web/api/HashRouter

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM