【问题标题】:Express not routing javascript files when URL has multiple directories当 URL 有多个目录时,Express 不路由 javascript 文件
【发布时间】:2019-06-16 10:51:16
【问题描述】:

我正在为使用 React-Router v4 的 React 应用程序设置服务器后端。到目前为止,我已经设置了 Express,以便将任何请求重定向到 index.html,从而允许 React Router 完成其余的工作。这适用于路由'/beats''/loops''/kits' 等。当 url 中有多个目录时会出现问题,例如 url '/beats/1/name-of-beat' (在 react- 中解析为 '/beats/:id/:name?'路由器)。

使用此快递代码:

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

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

这会将所有到 /kit、/beats 等的请求重定向到 index.html,并且所有 <script> 源仍然可以工作。但是,当尝试访问'/beats/1/name' 时,会提供 index.html,但 <script> 标记也会提供 index.html,导致 index.html 在浏览器中加载但没有 javascript。

如果我在 url 中添加除第一个目录之外的任何其他目录,则会发生这种情况,因此 '/beats/example''/beats/1/2/3' 但不适用于 '/example'(这将正确显示在 react-router 中配置的 404)。

如果需要,这里是路由器代码:

<Router>
    <div className="App">
        <Header />
        <Switch>
            <Route exact path="/" component={Home} />
            <Route path="/kits" component={Kits} />
            <Route exact path="/beats" component={Beats} />
            <Route path="/beats/:id/:beatName?" component={SoundPage} />
            <Route path="/loops" component={Loops} />
            <Route path="/contact" component={Contact} />
            <Route component={NoMatch} />
          </Switch>
    </div>
</Router>

这是构建的 index.html 脚本标签:

<script src="./static/js/1.731b4af1.chunk.js"></script>
<script src="./static/js/main.498cadba.chunk.js"></script>

这是项目结构:

-frontend
  -build
    -static
    -index.html
  -src
  -public
-backend
  -server.js

【问题讨论】:

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


    【解决方案1】:

    长话短说,您的嵌套路由需要使用match 属性。您的路线将嵌套在下拉结构中,其中每个连续的Route 将包含在下一个匹配的Componentrender 方法中。观看此视频以了解我的意思: React Router V4 Nested Routes

    使用动态嵌套路由的替代方法是使用查询参数结构,其中/beats/:query 将是/beat/find?id=12345&amp;beatName="Example Beat",您可以在此处找到示例: React Router V4 Nested Routes Match Params Not Accessible At Root Level

    第一个示例在论坛(如 Reddit)中更为常见,而第二个示例在网络店面(如亚马逊)中更为常见。

    【讨论】:

    • 解决方案:我听取了您的建议来嵌套我的路线,但是,我通过单独的解决方案解决了这个问题。问题实际上出在构建的 index.html 中,它使用./static/js/bundle.js 采购&lt;script&gt;。领先的 . 来自于使用自定义主页(在 package.json 中)构建。删除 &lt;script&gt; 的 src 中的 . 解决了该问题。
    猜你喜欢
    • 2020-08-12
    • 1970-01-01
    • 1970-01-01
    • 2011-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-24
    相关资源
    最近更新 更多