【问题标题】:Express overwrites react-router client side routesExpress 覆盖 react-router 客户端路由
【发布时间】:2016-10-06 18:55:23
【问题描述】:

我不想使用服务器端渲染,因为开始工作绝对是一件痛苦的事,而且没有它我已经让一切正常工作。

但是,如果我创建一个像 /test 这样的新网址并访问 localhost:3000/test 我会得到 Cannot get /test

这就是我的索引页面的服务方式

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

路由文件

const routes = (
    <div>
      <Route path="/" component={ AppContainer }>
        <IndexRoute component={ RegistrationContainer }/>
        <Route path="test" component={ StripeContainer }/>
      </Route>
  </div>
)

export default routes

【问题讨论】:

    标签: node.js express reactjs react-router


    【解决方案1】:

    我现在正在处理这个问题,我认为您需要在 React 路由之前声明 /test 路径。

    我将如何在我的应用程序中实现它是在 Express 中声明一些路由以供用户登录,然后在最后有一个总括将其他任何内容发送到 React。

    有点像

    app.get('/login', function(...));
    app.get('/logout', function(...));
    app.get('*', <TO-REACT>);
    

    我不确定这是否是处理此问题的正确方法,但应该可以。

    让我知道它是如何为您工作的,或者如果您预见到使用它会出现任何问题。

    更新: 我可以确认这现在对我有用。 这是我的快速路由文件和基本 React 文件的缩写版本。

    路线

    // redirects any requests to root of domain to React (a polling app)
    app.get('/', function(req, res) {
        res.redirect('/polls');
      });
    
    // authentication routes
    app.get('/login' function(....));
    app.get('/logout' function(....));
    app.get('/login/callback' function(....));
    app.get('/login/authorise' function(....));
    
    // React catch all route
    app.get('*', function(....{sendfile....});
    

    基础反应文件

    import React from 'react';
    import ReactDOM from 'react-dom';
    import {Router, Route, Redirect, browserHistory} from 'react-router';
    
    const PollListScreen = require('./PollListScreen.js');
    const PollAdd = require('./PollAdd.js');
    
    ReactDOM.render(
      (
      <Router history={browserHistory}>
        <Route path='/polls' component={PollListScreen} />
        <Route path='/polls/new' component={PollAdd} />
      </Router>
      ), document.getElementById('app')
    );
    

    【讨论】:

    • 使用这种方法,您如何使用 express.static 定义静态内容(如图像)的路由?现在,如果我尝试 GET /images/logo.png 服务器返回我的 index.html
    • 我的路线前有以下内容 - app.use('/css', express.static(path + '/static/css'));