1

我正在尝试制作一个应用程序来生成 Twitter 字数的“实时”图表,基本上是尝试在 24 小时内扩展和练习 NodeJS 的第 14 章。我决定使用“人力车”,我想我会从简单的例子开始。但是,虽然我可以加载一个简单的 html 页面,但我无法显示图表。Firefox 调试指示:“ReferenceError: Rickshaw is not defined [Break On This Error] graph = new Rickshaw.Graph( { " 。这意味着存在引用错误,但经过几个小时的谷歌搜索和阅读,我没有看到了。目录结构是正确的;npm 正确安装了所有模块,没有错误。任何人都可以看到我缺少什么吗?

注意:我是 JS/Node 的新手,虽然这本书在 Express 2.x 中工作,但我一直在 Express 3.x 中工作,所以不确定我是否在所有情况下都得到了正确的翻译。代码如下:

包.json

    {
    "name":"socket.io-twitter-example",
    "version": "0.0.1",
    "private": "true",
    "dependencies": {
        "express": ">=2.5.4",
        "rickshaw": ">=1.1.0"
        }
    }

应用程序.js

    var express = require('express'),
        rickshaw = require('rickshaw'),
        app = express(),
        http = require('http'),
        server = http.createServer(app)

    server.listen(3000);
    app.get('/', function (req,res) {
        res.sendfile(__dirname + '/index.html');
    });

索引.html

    <!DOCTYPE html>
    <html lang="eng">
        <head>
            <meta charset="UTF-8" />
            <title>Socket.IO Twitter Example</title>
        </head>
        <body>
            <h1>Rickshaw Example</h1>


            <div id="chart"></div>
            <ul class="tweets"></ul>

            <script type="text/javascript" src="node_modules/rickshaw/vendor/d3.v2.js"></script> //don't think "node_modules/" is required, but doesn't work without either
            <script type="text/javascript" src="node_modules/rickshaw/rickshaw.min.js"></script>

            <script>
                graph = new Rickshaw.Graph( {
                    element: document.querySelector("#chart"), 
                    width: 285, 
                    height: 180, 
                    series: [{
                        color: 'steelblue',
                        data: [ 
                            { x: 0, y: 40 }, 
                            { x: 1, y: 49 }, 
                            { x: 2, y: 38 }, 
                            { x: 3, y: 30 }, 
                            { x: 4, y: 32 } ]
                    }]
                });
                graph.render();
            </script> 


        </body>
    </html>
4

1 回答 1

2

You need to configure express.static middleware so that express knows where to look for static resources like js and css files:

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

Its common to put such resources into a public folder (as shown in the example above) or static folder.

If you create a public folder and organize it like

app.js
public
  rickshaw
    vendor
      d3.v2.js
    rickshaw.min.js

then you'll be able to have the files correctly loaded in your html using

<script type="text/javascript" src="/rickshaw/vendor/d3.v2.js"></script>
<script type="text/javascript" src="/rickshaw/rickshaw.min.js"></script>

See this section of the express docs for more info on and examples of middleware.

于 2013-08-01T01:39:28.547 回答