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

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

问题描述

我正在使用反应路由器来定义路由.我正在使用 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);

推荐答案

你必须配置你的网络服务器来为你定义的所有路由提供相同的页面,或者在 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 服务器通常不会注意到这些事情.他们知道如何提供 URL.当您请求 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天全站免登陆