【问题标题】:How can I serve external css/js files to html files displayed by a NodeJS app?如何将外部 css/js 文件提供给 NodeJS 应用程序显示的 html 文件?
【发布时间】:2016-03-12 22:17:59
【问题描述】:

我想仅使用 NodeJS 或非常轻量且灵活的其他方式在给定的 URL 处提供 html 文件。我已经能够使用 Express 提供这些 html 页面,但有些东西我不喜欢(事实上我们必须使用公用文件夹和所有依赖项),并且外部 css/js 只是不加载。

我在 server.js 文件中使用了一些东西,例如:

app.get('/', function() { app.sendFile('index.html')});

并且在 index.html 文件中:

<link rel="stylesheet" href="style.css">

所有文件都在同一个文件夹中。

【问题讨论】:

    标签: javascript html css node.js express


    【解决方案1】:

    express 中,您可以使用static 中间件。

    在下面的示例中,您定义了public 目录来存储它。

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

    现在您可以将您的style.css 放入此文件夹,它将作为静态内容提供。

    更多关于中间件:http://expressjs.com/en/guide/using-middleware.html

    【讨论】:

      猜你喜欢
      • 2017-05-10
      • 1970-01-01
      • 2015-10-15
      • 2020-09-25
      • 1970-01-01
      • 2020-08-04
      • 2017-01-27
      • 2017-05-14
      • 1970-01-01
      相关资源
      最近更新 更多