【问题标题】:bower_components not loading with express staticbower_components 未使用 express static 加载
【发布时间】:2016-07-17 19:21:54
【问题描述】:

我正在使用 bower 制作一个快速应用程序,但不知何故找不到 bower_components 文件夹。我在这里搜索过,尝试了所有解决方案,但没有任何效果。

在我的 server.js 中,我有:

/server/app.js

// Set static files
app.use(express.static('app'));
app.use('/bower_components', express.static(__dirname + '/bower_components'));

在索引中

/app/index.html

<link rel="stylesheet" href="/bower_components/bootstrap/dist/css/bootstrap.css" /></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular/angular.js"></script>   
...

我得到了什么:

GET http://localhost:3000/bower_components/bootstrap/dist/css/bootstrap.css 
(index):85 GET http://localhost:3000/bower_components/jquery/dist/jquery.js 
(index):86 GET http://localhost:3000/bower_components/angular/angular.js 

Cannot GET /bower_components/bootstrap/dist/css/bootstrap.css
...

如果我从标签中删除“/bower_components”前缀,然后在服务器中更改为:

server.js
app.use(express.static('bower_components'));

index.html
<link rel="stylesheet" href="/bootstrap/dist/css/bootstrap.css" />

【问题讨论】:

  • 您的 bower_components 文件夹是否在您的服务器文件夹中?否则代码错误。
  • 不,我的 bower_components 在根目录中。
  • 然后尝试下面建议的修改

标签: javascript node.js express bower


【解决方案1】:

这应该是由服务器文件夹之外的 bower_components 文件夹引起的。将server/app.js 处的代码修改为:

var path = require('path');

app.use('/bower_components', express.static(path.dirname(__dirname) + '/bower_components'));

这里我使用来自path 内置nodejs 包的dirname() 函数来获取服务器文件夹的父文件夹。

【讨论】:

  • 谢谢!!完美运行。我试过“path.join”,但不是这个。
  • 如果这能解决您的问题,请将其标记为正确答案
猜你喜欢
  • 1970-01-01
  • 2014-07-14
  • 1970-01-01
  • 1970-01-01
  • 2017-07-01
  • 2015-12-09
  • 2021-07-29
  • 2023-04-04
  • 2015-11-19
相关资源
最近更新 更多