【问题标题】:React router open page using URL使用 URL 反应路由器打开页面
【发布时间】:2019-01-15 14:52:22
【问题描述】:

我是反应编程的新手。试图解决我自己的问题,但遇到了以下问题。

我有以下反应路由器代码。

import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'; 

class Main extends Component {

render() {   
        return ( 
    <Router>
     <Switch>
       <Route exact path='/' component={Content} />   
       <Route path='/user/:id' component={User} /> 
       <Route path='*' component={NotFound} />
     </Switch>  
    </Router>
    );
}

export default Main

在内容中有带有照片的用户列表。如果我点击人物照片,它会将我重定向到特定用户。

我的代码如下:

<Link to={'/user/' + userItem.id}>
     <img className="useritem-img" src={userItem.photo} alt={userItem.tagline}/>
</Link> 

它将使用新 URL 正确打开用户组件,例如:http://localhost:3000/user/457365 点击照片。

但是,当在新标签中复制并粘贴相同的 url 时,它不会打开。可能是我在某些地方错了。

任何帮助将不胜感激。

编辑:

当我打开该页面时出现以下错误:

无法获取 /user/457365

我没有使用 create-react-app 只是简单的反应应用程序。

下面是我的 server.js

app.use(express.static('dist'));

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

app.listen(port, function (err) {
  if (err) {
        console.log(err);
    } else {
        open('http://localhost:' + port);
    }
})

【问题讨论】:

  • 这是使用create-react-app 吗?
  • 但是不要在你的控制台中出现任何错误?
  • 你是使用服务器端语言还是仅仅响应 js 应用程序?
  • 当您将整个 url 复制并粘贴到浏览器中时,浏览器会询问您的服务器服务器上是否存在具有此类路由的文件。当然不是因为您正在创建 SPA。因此,您的服务器需要将 index.html 返回到任何传入请求。
  • @apokryfos 当然,“静态”资产除外 ;-)(即 js 文件、css 文件、图像等)

标签: javascript reactjs react-router


【解决方案1】:

如果您收到该错误,则表示服务器正在尝试处理路由。因此,您应该确保服务器允许 SPA 处理路由。

例如,如果您使用express,您可能想要执行以下操作:

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

app.get('/api/whatever', (req,res) => {
  // Whatever your api does
});

// Allow the SPA to take care of the routing
app.get('*', (req,res) =>{
    res.sendFile(path.join(__dirname+'/client/build/index.html'));
});

【讨论】:

  • 谢谢。在 webpack 中添加以下内容后,我进行了管理。 output: { publicPath: '/' }, devServer: {\ historyApiFallback: true }
  • @ketan 你从来没有提到你使用 webpack dev-server 的事实。事实上,您明确表示您使用的是自己的快递服务器¯_(ツ)_/¯ 无论如何,我很高兴知道您发现了问题。
  • @ketan 鉴于您提供的信息量,我认为我的回答应该被标记为已接受。因为问题实际上是服务器阻止客户端处理路由。
猜你喜欢
  • 2020-04-28
  • 2022-06-14
  • 1970-01-01
  • 2021-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-27
相关资源
最近更新 更多