简体   繁体   English

如何让 Express 服务器使用 React 路由?

[英]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.以前我的服务器在端口 5000 上运行,我的 react 应用程序在端口 3000 上运行。我将通过端口 3000 访问它,它会对端口 5000 进行 API 调用。

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. 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.我是 MERN 堆栈的新手,这是我第一次尝试让服务器发送构建文件。 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.我的猜测是我必须重写 app.get 才能发送正确的文件,但我的构建只有一个文件,所以 IDK 该怎么做。 I'd rather not have to rewrite my whole server.我宁愿不必重写我的整个服务器。

You have no .htaccess and no nginx and any other URL redirector here.您在这里没有.htaccessnginx和任何其他 URL 重定向器。 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. React route 在浏览器上进行路由。 but in here routing is done in server side.但在这里路由是在服务器端完成的。 you should always return index.html in react application no mater which url you request.无论您请求哪个 url,您都应该始终在反应应用程序中返回 index.html。

if you want to work with both server side routing and browser routing, you may use HashRouting in react如果你想同时使用服务器端路由和浏览器路由,你可以在反应中使用 HashRouting

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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