【问题标题】:Index.html doesn't load css nor script on nested urlIndex.html 不会在嵌套 url 上加载 css 或脚本
【发布时间】:2018-10-28 06:47:15
【问题描述】:

我的 React 应用的起点是:

本地主机:3000/管理员

所以当我输入网址时:

localhost:3000/admin/dashboard/

一切正常。但是当我写下一个嵌套的url时:

localhost:3000/admin/dashboard/new

index.html 没有加载我的脚本和 css。当我在 index.html 中将 src url 从 ./js/admin-app.js 更改为 ../../js/admin-app.js 时,它可以工作,但在其他 url 上却没有。

本地主机:3000/admin/dashboard

我尝试在 index.html 基础中设置href="./",但它不起作用。

我找不到问题。

我的 server.js:

app.use('/admin', express.static(path.join(__dirname, 'admin/server/static/')));
app.use('/', express.static(path.join(__dirname, 'server/static/')));

app.get('/admin/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'admin/server/static/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
});

app.get('/*', function(req, res) {
  res.sendFile(path.join(__dirname, 'server/static/index.html'), function(err) {
    if (err) {
      res.status(500).send(err)
    }
  })
});

索引.html:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <base href="./" />
    <title>AdminPage</title>
    <link rel="stylesheet" href="css/admin_style.css">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  </head>
  <body>
   <div id="admin-app"></div>
   <script src="js/admin_app.js"></script>
  </body>
</html>

解决方案
我的应用程序运行在

本地主机:3000/admin/

代替

 src="js/admin_app.js" or src="./js/admin_app.js"

我试试这个

 src="/admin/js/admin_app.js" 

而且效果很好

【问题讨论】:

  • 嗨,欢迎来到 SO。您能否发布您的 index.html 和您的 app.js 或您的基本 js 文件是什么?
  • 嗨,谢谢 :) 我在下面发帖
  • edit您的问题并在那里添加代码。不要将其添加为答案。请将该代码移至您的问题,并删除您的答案。
  • 嗨,对不起。我编辑我的帖子
  • 请标记正确答案。

标签: reactjs react-router


【解决方案1】:

我们可以尝试几件事。

设置 index.html 时,让文件相对于基本 url。

所以,而不是:

<script src="js/admin_app.js"></script>

使用:

<script src="/js/admin_app.js"></script>

这意味着浏览器将始终在相对于基础应用的 url 中搜索文件,例如:

http://localhost/js/admin_app.js

或类似的东西:

http://myurl.com/js/admin_app.js

因此,您的 admin_app.js 文件必须位于该文件夹 (js) 中。在您的情况下,您有一个像这样的静态文件夹结构:

server/static

所以文件必须在:

server/static/js/admin_app.js

这是因为在您的服务器中,您将所有到 / 的请求路由到文件夹 server/static/

基本上,您必须使用您的文件夹结构指向正确的文件。您还有一个名为 admin 的文件夹,因此如果文件位于 admin/server/static 中,则相对 url 应为:

<script src="/admin/js/admin_app.js"></script>

所以,这完全取决于文件在您的文件夹结构中的确切位置。

对 css 做同样的事情:

<link rel="stylesheet" href="/css/admin_style.css">

<link rel="stylesheet" href="/admin/css/admin_style.css">

从你的index.html file 中删除它(你不需要它):

<base href="./" />

【讨论】:

  • 嘿,非常感谢。我试过 /js/admin_app.js 但没有帮助。我在 /admin 之前添加。 /admin/js/admin_app.js 现在可以完美运行了。 :)
  • @DennisM。很好,如果对您有帮助,请考虑将其标记为正确答案,并对其进行投票。谢谢!
猜你喜欢
  • 2017-12-31
  • 2017-07-19
  • 2015-01-20
  • 2020-07-20
  • 1970-01-01
  • 1970-01-01
  • 2022-01-01
  • 2018-04-02
  • 1970-01-01
相关资源
最近更新 更多