【问题标题】:Node.js: JustGage is not definedNode.js:未定义 JustGage
【发布时间】:2018-07-30 13:44:33
【问题描述】:

我正在尝试编写一个简单的基于 node.js 的应用程序,它可以使用 JustGage(基于 JavaScript 的插件)。以下是我的 Node.js 应用程序。

var http = require('http');
var fs = require('fs');

http.createServer(function (req, res) {
  fs.readFile('index.html', function(err, data) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(data);
    res.end();
  });
}).listen(8080);

下面是 index.html 页面。

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Temperature Sensor</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script type="text/javascript" src="static/resources/js/justgage.js"></script>
  <script type="text/javascript" src="static/resources/js/raphael-2.1.4.min.js"></script>

  <script>
    window.onload = function(){
      var g = new JustGage({
        id: "g_a411_faculty",
          value: 22, 
          min: 10,
          max: 40,
          title: "A411 - Faculty Office",
          label: "Celsius",
          levelColors: [
            "#ffffff",
            "#f9c802",
            "#FF0000"
          ]
      });
    };
  </script>
</head>
<body>
<div id="g_a411_faculty" class="col-sm-6" style="width:400px; height:320px"></div>
</body>
</html>

当我运行代码并在 Google Chrome 中打开 http://localhost:8080 时,索引页面显示未定义 JustGage 的错误(在开发人员工具中)。但是,当我在 Chrome 中简单地打开 index.html(不使用 Node.js)时,页面可以正常工作。你能帮忙看看我哪里错了吗?

我尝试通过安装justgage包来解决问题

npm install justgage

但是,当我写的时候

var jg = require('justgage');

这显示了一个参考错误 - 文档未定义。请帮忙!

【问题讨论】:

    标签: javascript html node.js npm justgage


    【解决方案1】:

    node.js 没有为您的静态文件夹提供服务。

    网站在直接从文件夹运行时可以正常工作,因为您可以从同一位置访问static/... 的相对路径。

    当您通过 node.js 运行时,您只提供 index.html 而不是相关资产。

    this 线程中讨论了一些提供静态文件/文件夹的有用方法

    【讨论】:

    • 那是正确的!我创建了一个 http-server 来托管剩余的文件,然后在 src 选项中使用该链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-04
    • 2017-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    • 2015-11-14
    相关资源
    最近更新 更多