0

我有一个简单的网络应用程序与创建反应,应用程序和表达。反应路由器不能GET /路由后才部署到Heroku

使用反应路由器制作的所有页面都可以在本地正常工作,以及在我自己的机器上在线一旦部署到Heroku。

但是,在其他机器在线测试后,我无法访问这些页面 - 每当我点击他们来说,这显示Cannot GET /*route*

我仍然有*名称的链接* .herokuapp.com域如果影响以任何方式

我使用重定向代码如下:(我用的火力和反应,引导和)

class App extends Component { 
render() { 
    return (
     <div> 
      <MyNavbar/> 
      <Switch> 
       <Route exact path="/" component={Home}/> 
       <Route exact path="/eateries" component={Eateries}/> 
       <Route exact path="/thank-you" component={ThankYou}/> 
      </Switch> 
     </div> 
    ); 
} 

重定向到/感谢信:

componentWillMount() { 
    firebase.auth().onAuthStateChanged((user) => { 
     if (user) { 
      window.location = "thank-you" 
     } 
    }) 
} 

所以基本上,当通过一个模式组件在用户的迹象,应该带他们去/感谢信

重定向到/餐馆:

<NavItem href="/eateries"> 
    For Eateries 
</NavItem> 

是不是有什么毛病我的方式m重定向用户还是一般使用反应路由器?

+0

很难说没有更多的信息,但'window.location'应链接到'/ thank-you' –

+0

你需要什么信息? – VWang

回答

0

很难知道没有看到你的服务器代码 - 但为了支持react-router的渲染机制,则需要使用通配符路径在您的服务器代码:

app.get('*', (req, res) => res.sendFile(path.resolve('build', 'index.html')); 

这基本上意味着“为任何路由尚未匹配,发送index.html文件“,然后将加载您的webapp,这反过来将处理路由。请注意,您需要在此之前添加为您的资产提供服务的静态中间件 - 这是我多次忘记的陷阱。大多数服务器文件会再看看这样的:

const express = require('express'); 
const app = express(); 

app.use(express.static('build')); 
app.get('*', (req, res) => res.sendFile(path.resolve('build', 'index.html')); 

app.listen(process.env.PORT,() => console.log('listening for connections')); 

现在,这似乎工作,要么在本地方式,因为你的web应用程序已经加载,并处理路由给你的。

但是,我注意到您在重定向您的用户时使用了window.location。这使得一些浏览器至少(可能全部)从服务器请求新页面,而不是让应用程序处理它。而应使用提供的history属性,其中包含push方法。

componentWillMount() { 
    firebase.auth().onAuthStateChanged((user) => { 
    if (user) { 
     this.props.history.push('/thank-you'); 
    } 
    }); 
} 

这增加了一个新的条目到历史堆栈。如果您想要定期重定向,则应该使用.replace

希望这会有所帮助!