【问题标题】:How to load my css and js files with node.js [duplicate]如何使用 node.js 加载我的 css 和 js 文件 [重复]
【发布时间】:2019-01-07 19:04:05
【问题描述】:

我看过很多类似的问题,但我无法让它发挥作用,所以我自己问吧

我有一个这样的文件夹:

Source Code
  Frondend
    Graphs.html
    Graphs.css
    Temperature.js
  Server_Backend
    server.js

我想用 node.js 运行这些文件,如果需要我也可以使用 express。

我在 server.js 中有这个来加载我的 html:

fs.readFile('../Frondend/Graphs.html', function (err, html) {

    if (err) throw err;

    http.createServer(function(request, response) {
        response.writeHeader(200, {"Content-Type": "text/html"});
        response.write(html);
        response.end();
    }).listen(8080);
});

这些是我的 html 标头中的链接:

<script type="text/javascript" src="Temperature.js"></script>
<link rel="stylesheet" type="text/css" href="Graphs.css">

如何同时包含我的 css 和 js 文件?正如我所说,我已经尝试了很多东西,但我似乎无法让它发挥作用。

【问题讨论】:

    标签: javascript html node.js express


    【解决方案1】:

    所以浏览器会做什么,在你发送 html 之后(你做得很好),它会寻找 http://yourdomain.com/Temperature.jshttp://yourdomain.com/Graphs.css。为了让 express 将这些暴露给浏览器,express 具有express.static 函数。

    使用 express 时可以这样做

    app.use(express.static('./Frondend'));
    

    这将接受对您网站的任何请求,并检查Frondend 文件夹中是否有文件,如果有,将发送该文件。

    希望这是有道理的:)

    【讨论】:

    • 它不工作,但可能有其他事情出错 idk,它是否可能因为它位于不同的文件夹中而不起作用?从 Server_Backend 首先需要回到源代码,因为有 Frondend 文件夹。
    【解决方案2】:

    由于您是初学者,我会使用express.js。它使处理静态资产(css 和 javascript 文件)之类的事情变得更加容易,并帮助您将请求路由到不同的代码部分(例如 /users、/files、/about)

    要解决您的问题,最好先查看following information from express.js about static files,然后再查看the getting started guide

    【讨论】:

      猜你喜欢
      • 2018-04-19
      • 1970-01-01
      • 1970-01-01
      • 2018-05-27
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 2014-06-27
      • 1970-01-01
      相关资源
      最近更新 更多