【问题标题】:React router doesn't work on express serverReact 路由器在快速服务器上不起作用
【发布时间】:2018-12-16 02:14:49
【问题描述】:

我是新手,我正在尝试用它构建一个聊天应用程序。我使用 react-router 根据 url 加载不同的组件。在我的react项目文件夹(client/src/index.js)中,代码如下:

import {BrowserRouter as Router, Route} from 'react-router-dom';    
...
ReactDOM.render(
  <Router>
    <div>
      <Route exact path='/' component={App} />
      <Route path='/customer' component={CustomerPage} />
      <Route path='/support/:support_id' component={SupportPage} />
    </div>
  </Router>,
  document.getElementById('root')
);
...

当我使用“npm start”在 react 文件夹中启动它时,它会起作用。但是当我运行“npm run build”并使用快速服务器提供静态文件时,它只能在“/”路径中提供应用程序页面,而对于“/customer”和“/support/:support_id”路径,它会加载什么都没有。

在 express server 文件夹中,我通过以下方式加载静态文件:

服务器/app.js:

...
var indexRouter = require('./routes/index');
app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
app.use('/', indexRouter);
...

服务器/路由/index.js:

...
router.get('/', function(req, res) {
  res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
});
...

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript node.js reactjs router static-files


    【解决方案1】:

    React Router 在浏览器中完成所有路由,因此您需要确保将index.html 文件发送给每个路由的用户。

    这应该就是你所需要的:

    app.use('/static', express.static(path.join(__dirname, '../client/build//static')));
    app.get('*', function(req, res) {
      res.sendFile('index.html', {root: path.join(__dirname, '../../client/build/')});
    });
    

    【讨论】:

    • 这是与此相同问题相关的数十个问题中唯一正确的答案。其他人无视static 文件夹导致index.html 被提供而不是css、块等。@Hiber 请接受这个作为答案。
    • 正如@basse 所说,我在 Node.js + Koa + React 中遇到了这个问题,并用这个答案解决了。
    • 当我们想将 Express 和 React Router 合并到同一个项目中时,很难合并。在我看来,请小心加星号,因为它可能会影响您服务器的 URL。如果我们通过特定的名称定义客户端 URL 会更好,例如 /home /dasdboard /login /logout ...etc
    • 有了这个解决方案,我似乎仍然遇到index.html 被提供而不是css 和块文件的问题,但只能来自辅助子路由(即host:port/route 有效,但host:port/route/subroute 没有- 页面为空白,所有 css 和 js 资产再次只是 html 文件,由 `host:port/route/static//filename. 提供。)。任何想法为什么会发生这种情况?
    【解决方案2】:

    您必须提供静态文件并处理 index.js 中的任何请求:

    const express = require('express');
    const path = require('path');
    
    const app = express();
    
    // Serve the static files from the React app
    app.use(express.static(path.join(__dirname, 'client/build')));
    
    // Handles any requests that don't match the ones above
    app.get('*', (req,res) =>{
        res.sendFile(path.join(__dirname+'/client/build/index.html'));
    });
    
    const port = process.env.PORT || 5000;
    app.listen(port);
    
    console.log('App is listening on port ' + port);
    

    【讨论】:

      【解决方案3】:

      * 工作而不是在 app.get() 中使用 / 否则它将始终显示无法获取。谢谢@basse

      【讨论】:

      • 这还不足以提供足够的额外信息来做出回答。它实际上只是一个“谢谢”。这对于 StackOverflow 努力做到的 Q/A 对的集合来说并不是一个有价值的贡献。请edit 以增加此答案的实用性,或将其变成评论(一旦您收集了足够的声誉meta.stackexchange.com/questions/214173/…)
      【解决方案4】:

      摆脱这个障碍对我有帮助

      app.use(function(req, res, next) {
        next(createError(404));
      });
      

      【讨论】:

        【解决方案5】:
        app.get("/get/data/from/store", (req, res) => {
                     your sql codes here
          });
        

        // 您必须将上述所有 REST API 调用放在以下代码之前。 // 否则所有 url '*' 将被转发到 index.html

        // 通配符处理任何与 ABOVE 不匹配的请求

        app.use(express.static(path.join(__dirname, '/build')))

            app.get('*', (req, res) => {
              res.sendFile(path.resolve(__dirname+'/build/','index.html'));
            });
            app.listen(port, () => {
              console.log("Server running on port ", port);
            });
            
            put the wildcard app.get('* call at the end. Just before the app.listen.
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2018-09-04
          • 1970-01-01
          • 2016-04-16
          • 1970-01-01
          • 2020-08-12
          • 2020-01-15
          • 2019-01-13
          • 2020-05-18
          相关资源
          最近更新 更多