React JS:我的应用程序正常工作吗?

时间:2019-04-29 05:10:05

标签: javascript reactjs react-router

我已经建立了一个简单的待办事项应用程序链接http://todo-app.myartsonline.com/

对于导航,我使用了react-router-dom库

效果很好,但我的疑问是,当我们转到应用程序并单击说明时,效果很好,现在尝试此链接http://todo-app.myartsonline.com/Instruction 这会导致错误, 显然,由于应用程序尚未加载而发生错误!

是/如果存在,则如何解决。 如何直接显示

我的React导航代码

    import { Router, Route} from "react-router-dom";
    import history from './history.js';

    <Router history={history}>

    <Container fluid>

        <NavbarComponent />

          <Route path="/" exact component={Home} />
          <Route path="/Streams/list" exact component={StreamList} />
          <Route path="/Streams/new" exact component={StreamCreate} />
          <Route path="/Streams/edit" exact component={StreamEdit} />
          <Route path="/Streams/delete" exact component={StreamDelete} />
          <Route path="/Streams/show/:id" exact component={StreamShow} />
          <Route path="/Instruction" exact component={Instruction} />
          <Route path="/AboutProj" exact component={AboutProj} />
    </Container>

  </Router>

这是我的History.js

    var createHistory = require('history').createBrowserHistory;
     export default createHistory();

1 个答案:

答案 0 :(得分:2)

我假设您正在使用browserHistory

当您转到此链接http://todo-app.myartsonline.com/Instruction时,您的服务器不会返回index.html,因此react路由器不会起作用。 但是,当您转到http://todo-app.myartsonline.com/并路由到instruction时,这是客户端路由,服务器不知道该路由。

要使浏览器历史记录正常运行,您需要进行服务器端配置。对于所有请求,请在响应中发送index.html。这应该是请求顺序中的最后一个。

1)配置Express:-

app.get('/*', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'))
})

2)配置WebpackDevServer

devServer: {
  historyApiFallback: true
}

希望有帮助!