【问题标题】:Express Go To Direct Link In React Router/ReactExpress Go To Direct Link In React Router/React
【发布时间】:2017-12-29 04:28:42
【问题描述】:

我在我的项目中使用 React Router 4,当我直接在浏览器中输入 URL(如 localhost:8000/post/1)时,出现以下错误。

无法获取 /post/1

我在快递服务器上的代码是

app.get('/post/:id', function (req, res) {
  res.sendFile('./public/index.html', {root: __dirname});
})

我尝试在react-router-dom 上使用{HashRouter} 包来允许哈希爆炸,但它似乎也不能正常工作。

如何解决此错误?并允许在我的项目中直接链接。谢谢

【问题讨论】:

    标签: javascript node.js reactjs express react-router


    【解决方案1】:

    对于由节点服务的应用程序,其客户端处理路由,例如 React 和 React-router,您需要为每个请求提供 index.html。

    将这个(app.get)放在您的 express 应用程序中的任何 API 路由下方。

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

    这将确保向您的服务器发出的每个不是 API 调用的请求都将您的 index.html 提供给您的用户。一旦客户端有了 index.html,内部路由将由 React-routing 处理。

    【讨论】:

    • 我试过了,但是这样的网址是http://localhost:8000/post/1#/ 我想要的是http://localhost:8000/#/post/1
    • 此应用程序是否在网络浏览器中查看?如果是这样,您应该使用 BrowserRouter。如果您有一个旨在处理路由的 react-router,则上述内容应该可以直接导航到 http://localhost/post/1
    猜你喜欢
    • 2019-08-15
    • 2021-02-21
    • 2021-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-26
    • 1970-01-01
    相关资源
    最近更新 更多