【问题标题】:Include libraries or external stylesheets in Express在 Express 中包含库或外部样式表
【发布时间】:2026-01-17 21:10:01
【问题描述】:

我正在节点服务器上使用 express 框架构建一个待办事项应用程序...我有一个 index.ejs 文件作为我的应用程序的起点,当我尝试时,我将 jquery.min.js 文件放在同一个文件夹中将 jquery 文件包含为

<script src="jquery.min.js" type="text/javascript"></script>

我的应用无法加载它,当我在我的 chrome 中看到网络时,它会寻找

https://localhost:3000/jquery.min.js
我如何加载文件?

PS:我习惯于通过 cloud.google.com 通过将 url 放在 src 标签中来加载脚本,但我希望我的应用程序通过这种方法加载得更快

【问题讨论】:

    标签: javascript html node.js express


    【解决方案1】:

    您应该为静态文件创建一个 ./public 文件夹。

    将此行添加到您的 app.js 中所有路线的上方:

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

    然后在 index.ejs 中使用它:

    <script src="/jquery.min.js"></script>
    

    【讨论】:

    • 我的代码 github link 我在 src/configuration.coffee 中添加的行 & 我的 index.ejs 在 src/views 中...这给了我错误“参考错误:路径未定义”
    • 你必须require path 模块。 var path = require('path');path 模块记录在 nodejs.org/api/path.html
    最近更新 更多