Express不能呈现Bootstrap

4
我刚开始使用Express,正在尝试弄清楚为什么运行我的应用程序时,Bootstrap字体没有被渲染(它显示为简单的Times New Roman)。我相当确定我使用了正确的路径,因为当我在浏览器中打开我的index.html文件时,字体可以正确地渲染。我还尝试过使用Bootstrap导航栏,在通过Node运行时,Bootstrap似乎不能正常工作,但是在独立查看HTML文件时,它可以正常工作。将Bootstrap目录的路径更改为“/public/bootstrap…”会导致两种方式都无法正确呈现。我该如何解决这个问题?

index.html:

<html>
  <head>
    <title>X</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="../public/bootstrap/css/bootstrap.min.css" type="text/css" rel="stylesheet" media="screen">
  </head>
  <body>
    <script src="http://code.jquery.com/jquery.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <div class="container">
      <h1>Under Construction</h1>
      <p>This website is under construction. Come back soon!</p>
    </div>
  </body>
</html>

web.js(我的主要应用程序文件):

var express = require('express')

var app = express()
app.set('view engine', 'ejs')
app.engine('html', require('ejs').renderFile)

app.get('/', function(req, res) {
  res.render('index.html')
})

var port = process.env.PORT || 5000;
app.listen(port, function() {
  console.log("Listening on " + port);
})
2个回答

10

1) Bootstrap 和 Express 之间没有任何关系。Bootstrap 完全运行在客户端上,而 Express 是基于 Node.js 的服务器中间件库。

2) 为什么要自己提供 Bootstrap?最好使用 CDN:

  1. http://www.bootstrapcdn.com
  2. http://hostedbootstrap.com/

3) 如果您坚持自己提供,添加一个静态目录,以便 Express 可以提供静态文件(添加静态目录也可以在您尝试为您的网站提供 js / css,但仍然更喜欢从 CDN 提供 Bootstrap 时提供服务)。

app.use(express.static(path.join(__dirname, 'public')));

那么就不需要使用公共路径,只需使用指向你的 CSS 文件所在的根路径:

bootstrap/css/bootstrap.min.css

i.e. 

<link href="../public/bootstrap/css/bootstrap.min.css" type="text/css" rel="stylesheet" media="screen"

4
  1. 您需要一个实际的静态中间件。Express本身默认不会做任何事情。

    app.use(express.static(__dirname + "/public"));

  2. 不要在HTML路径中使用"public"。那是静态资源所在的目录,但从浏览器的角度来看,那是根目录。也不要使用相对路径。

.

 <link href="/bootstrap/css/bootstrap.min.css" type="text/css" rel="stylesheet" media="screen">

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接