【问题标题】:How to render/resolve react-router enpoints when being served from an express/node server [duplicate]从快速/节点服务器提供服务时如何渲染/解析react-router端点[重复]
【发布时间】:2021-01-11 04:56:11
【问题描述】:

我在从目录“/build”提供的反应前端应用程序中使用反应路由器, 我的快递服务器。所有非前端功能(数据库等)都来自端点“localhost:3003/api/something”,我有前端设置从“localhost:3003/”提供服务。

我遇到的问题是,当我从前端的主页(“localhost:3003/”)导航到其他地方时,例如“localhost:3003/drinks/1”,一切正常。但是,当我在“localhost:3003/drinks/1”重新加载浏览器或直接导航到该 URL 时,会出现“找不到端点”错误。

【问题讨论】:

    标签: node.js reactjs express react-router


    【解决方案1】:

    您必须在服务器端添加这些路由。

    SPA 处理每条路由的简单方法如下:

    app.get('*', handler);
    

    【讨论】:

      【解决方案2】:

      这个错误是因为 react-router 正在使用 history.pushState() 来解析端点,但是如果您重新加载服务器将尝试从服务器为您提供该端点,并且该端点对服务器不存在。 有一种方法可以告诉服务器将此渲染推迟到 react-router。

      app.get('/drinks/*', function response(req, res) {
        res.sendFile(path.join(__dirname, 'build', 'index.html'));
      });
      

      现在 index.js 将处理任何发往 localhost:3003/drinks/anything 的请求。意思是前端会被react-router相应渲染,而不是被express劫持。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-03-26
        • 2016-11-17
        • 1970-01-01
        • 2016-08-06
        • 1970-01-01
        相关资源
        最近更新 更多