React路由在Facebook的create-react-app构建中不起作用 [英] React routes are not working in facebook's create-react-app build

查看:101
本文介绍了React路由在Facebook的create-react-app构建中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用React Router定义路由。而且我正在使用 create-react-app 进行开发。我的问题是,如果我在地址栏中键入子页面的URL,然后尝试访问它在开发版本中有效,但在生产版本中无效。

I am using react router to define the routes. And i am using create-react-app for developments. My question is if i type the url for subpages in address bar and try to visit it works in development build but not in production build.

我正在使用一个简单的快递服务器用于托管生产版本

I am using a a simple express server for hosting the production build

var express = require('express'),
  app = express(),
  http = require('http'),
  httpServer = http.Server(app);

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

app.get('/', function(req, res) {
  res.sendfile(__dirname + '/index.html');
});
app.listen(3001);


推荐答案

您必须配置Web服务器,以便为您定义的所有路由,或在React中实现服务器端渲染。开发网络服务器可能是这样配置的,但是生产网络服务器(Apache?Nginx?其他?)不是这样配置的。 此问题可能会有所帮助。

You must configure your webserver to serve the same page for all the routes you've defined, or implement server-side rendering in React. The development webserver is probably configured as such, but the production one (Apache? Nginx? something else?) isn't. This question might help.

之所以如此,是因为React用于构建单页应用程序。您只有一个传统的网页,其中加载了一些脚本-最有可能是构建过程的输出,然后这些脚本会处理其他所有内容。这包括生成新的DOM,向服务器请求数据,甚至在视图改变时通过操纵URL来伪造多页面应用程序的行为。最后一点就是react-router的作用。

The reason why this is, is that React is used in building single page applications. You have a single traditional webpage, which loads some scripts - the output of your build process most likely, and then those scripts take care of everything else. This includes generating new DOM, making requests to the "server" for data, and even faking a multi-page app behaviour by manipulating the URL when views change. This last bit is what react-router does.

但是,Web服务器通常不会注意到这些事情。他们知道如何提供网址。而且,当您请求yourdomain.com/时,它们将在该主页上显示,但是当您请求yourdomain.com/some/page/123时,它们将不知道要提供什么内容,除非进行了特殊配置。一种配置是还返回这些其他URL的主页内容。 React-router会选择URL并使用适当的组件,因此一切看起来都很好>

However, web servers are usually oblivious to these things. They know how to serve URLs. And when you request yourdomain.com/ they'll serve that main page, but when you request yourdomain.com/some/page/123 they won't know what to serve, unless specially configured. And one configuration is to also return the contents of the main page for these other URLs. React-router will pick up the URL and use the proper components, so everything will look OK>

这篇关于React路由在Facebook的create-react-app构建中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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