【问题标题】:How to serve js file that needs to be executed on client side?如何提供需要在客户端执行的js文件?
【发布时间】:2016-02-22 07:35:00
【问题描述】:

如何使我的脚本文件可用于节点 js 中的 html 文件?

我的 server.js 文件如下所示

var express = require('express');
var app = express();

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

app.get('/', function (req, res) {
  res.sendFile(__dirname + '/index.html');
});

app.listen(3000, function () {
  console.log('listening!');
});

那么如何让 app.js 文件中的脚本执行呢?

<!doctype html>
<html>
<head>
  <title>Chat room</title>
</head>
<body>
  <form>
  <input type = "text" name = "message">
  </form>
</body>
<script src = "app.js"></script>
</html>

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    您需要将 javascript 文件放在 /public 或 /public 的子目录中。然后从 index.html 中引用该文件。

    现在 index.html 正在 __dirname 中查找 javascript 文件,但在您的代码中您公开了 __dirname + '/public'。

    【讨论】:

      【解决方案2】:

      您已将公共可用文件夹设置为public,因此您的.js.css、...文件应该在此文件夹中。公共文件夹的典型结构是这样的:

      如果你有如上图所示的目录结构,你会像这样引用你的 JavaScript 文件:

      <script src = "/javascripts/app.js"></script>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-04-19
        • 1970-01-01
        • 2012-01-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多