反应应用程序中的路由问题 [英] Issue with routing in react app

查看:33
本文介绍了反应应用程序中的路由问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个网络应用.后端使用节点,前端使用 React.设置(简化)如下:

I have a web app. Back end with node and front end with React. Setup (simplified) goes like this:

index.js (the server)
client
package.json

客户

现在,client 文件夹包含一个前端 Web 应用程序,其内容与您键入 create-react-app 时得到的内容基本相同.

Now, the client folder contains a front end web application, its contents are basically same as what you get when you type create-react-app.

client 里面有一个 build 文件夹,我通过在 client 中运行 npm run build 创建了它文件夹.

Inside client there is a build folder which I created by running npm run build from within the client folder.

服务器

现在,我的主文件夹中的 index.js 充当节点服务器,在其中我有如下一行:

Now, the index.js from my main folder acts as the node server, inside it I have a line like:

app.use(express.static(__dirname + "/client/build"));

使用这种方法,我合并了我的节点服务器和客户端前端应用程序(位于客户端文件夹内).你可以看到我告诉服务器从 client/build 提供文件.

Using this approach I have merged my node server and a client front end application (located inside client folder). You can see I told the server to serve files from the client/build.

一切正常,直到我遇到这个.

All was working fine, till I encountered this.

如果我单击客户端应用程序中的反应按钮,该按钮使用以下命令手动调用路由器:

If I click a react button in my client app which manually calls my router using say:

this.props.router.push('/listmovies');

它正确地显示了页面.

但是如果我在 URL 地址栏中输入相同的页面并按 ENTER 我会得到错误:

But if I type same page in URL address bar and hit ENTER I get error:

无法获取/listmovies

Cannot GET /listmovies

我很确定后一个错误来自节点服务器.因为在 index.js 中没有 listmovies 的监听器(也不应该有).你看基本上我认为节点正在拦截调用并给我一个错误.而在我之前调用 router.push 的情况下,我得到了一个正确的页面.

The latter error I am pretty sure comes from node server. Because there is no listener for listmovies in index.js (and there should not be). You see basically I think node is intercepting the call and giving me an error. Whereas in my former case where I called router.push I get a correct page.

我希望我能解释我的问题.有人可以帮忙解决这个问题吗?

I hope I managed to explain my problem. Can someone help how to solve this issue?

推荐答案

您必须使 express 应用程序将所有请求重定向到主 React 文件,以便 react-router 可以接管.app.use 下方的类似内容.

You have to make the express application redirect all requests to the main React file so react-router can take over. Something like this below the app.use.

  app.get('*', function(req, res) {
        res.sendFile(__dirname + '/client/build/index.html')
    })

这基本上处理所有通配符并将其指向index.html.请注意,如果您还在 express 应用程序上实现 API 路由,请将它们置于此通配符语句之上,否则它会拦截它们并将它们视为客户端 react-router 路由服务器端 API 路由.

This basically handles all wildcards and points it to the index.html. Mind you if you are also implementing API routes on the express app have them above this wildcard statement because otherwise it will intercept them and treat them as client side react-router routes instead of server-side API routes.

这篇关于反应应用程序中的路由问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆