【问题标题】:D3.js not defined, express serving up static filesD3.js 未定义,表示提供静态文件
【发布时间】:2017-05-11 18:34:34
【问题描述】:

我有快速提供静态 js 文件的服务,其中包括 d3.js (v4) 的本地副本。所有其他 js 文件都从我的标签加载,但它说 d3 未定义。我也尝试从 url 加载,但没有骰子,jquery 加载正常(“https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js”)但不是 d3(“https://d3js.org/d3.v4.min.js”)。

显然它能够找到资源,因为我没有得到 404,但它永远不会运行。当我将 console.log('hello') 扔到 d3 源中时,它没有显示出来。

我已经在 Chrome 和 Firefox 中尝试过。我已经看到了使用 http-server 的答案,但是 express 的静态服务器不是在做同样的事情吗?

如果您有任何想法,请提前致谢。

文件结构:

app.js:

const express = require('express');
const app = express();
const router = express.Router();
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const path = require('path');

const routes = require('./routes');
const graph = require('./graph');

//urls to use
const localMongoUrl = "mongodb://localhost:27017/test";

const url = localMongoUrl

//connect to db. make sure mongo daemon is running.
mongoose.connect(url);
const connection = mongoose.connection;

connection.on('error', err => console.err(err));
connection.on('open', err => {
  if (err) console.err(err);
  else console.log('connected to ' + url);
});

//middleware attaches form info to req.body
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

//set up pug as the templating engine
app.set('view engine', 'pug');

//serve up files in public folder
app.use(express.static('public'));

//setup router as middleware
app.use('/', router);

//serve up the index page when root is hit
router.get('/', (req, res) => {
  connection.db.listCollections().toArray((err, collections) => {
    if (err) {
      console.log(err);
      res.json(err);
      res.end();
    } else {
      const collectionNames = collections.map(collection => {
        return collection.name;
      })
      req.collectionNames = collectionNames;
      res.render('layout', { names: req.collectionNames, url: url });
    }
  });
})

//route for when user selects which collection in dropdown
router.use('/collections', routes);
router.use('/graph', graph);

//listen for requests
app.listen(3000, () => {
  console.log('Listening on 3000');
});

graph.pug

html
  head
    title GateCounts Graph
    link(rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css")
    link(rel="stylesheet" href="/css/styles.css")
    link(rel="stylesheet" href="/css/barchart.css")
    link(rel="stylesheet" href="/css/pikaday.css")
  body
    .page-wrapper
      .row
        .col-md-2
          h1 D3 Graph w/ Mongodb
          .form-wrapper#graph-query
            form(method="POST" action="/graph/getgraph")
              fieldset.form-group
                legend Date Range
                  input.form-control(type="text" id="fromDate" name="fromDate" placeholder="From:")
                  input.form-control(type="text" id="toDate" name="toDate" placeholder="To:")
              fieldset.form-group
                div.form-check
                  label.form-check-label(for="sunday") Sunday&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="sunday" name="weekdays" value="1" checked)
                div.form-check
                  label.form-check-label(for="monday") Monday&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="monday" name="weekdays" value="2" checked)
                div.form-check
                  label.form-check-label(for="tuesday") Tuesday&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="tuesday" name="weekdays" value="3" checked)
                div.form-check
                  label.form-check-label(for="wednesday") Wednesday&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="wednesday" name="weekdays" value="4" checked)
                div.form-check
                  label.form-check-label(for="thursday") Thursday&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="thursday" name="weekdays" value="5" checked)
                div.form-check
                  label.form-check-label(for="friday") Friday&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="friday" name="weekdays" value="6" checked)
                div.form-check
                  label.form-check-label(for="saturday") Saturday&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="saturday" name="weekdays" value="7" checked)
              fieldset.form-group
                div.form-check
                  label.form-check-label(for="sunday") Include Closed Days?&nbsp&nbsp
                    input.form-check-input(type="checkbox" id="includeClosed" name="includeClosed" value="true" checked)
              button.btn(type="submit") Submit
              hr
          .summaryBox
            h4 Summary
            ul.list-group#summary-list
        .col-md-10
          h4 GateCounts Graph
          .graphBox
            #graph
script(src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js")
script(scr="js/d3.js")
script(src="js/barchart.js")
script(src="js/pikaday.js")
script(src="js/initGraph.js")
script(src="js/events.js")

【问题讨论】:

  • 也许尝试不使用CDN?
  • 我也试过本地下载的副本,结果一样。
  • 你有一些代码要给我们看吗?
  • express 需要额外的编码,而http-server 不需要任何东西,它只是服务
  • 当然,不知道该分享什么,我已经包含了我的 .pug 模板和 app.js

标签: javascript node.js express d3.js


【解决方案1】:

您在app.js 所在的同一目录下的./public 目录中提供静态文件。在该文件夹下,您需要有一个js 目录和d3.js。如果您安装了D3 from npm,那么它将在您的<project root>/node_modules 中,您需要从那里找到d3.js 并将其复制过来。您可以使用大量工具自动执行构建任务。

确保文件在public/js 中并且正确无误。然后再试一次。

编辑:补充一点,如果您在开发工具中检查您的网络选项卡并且您不是 404,请转到要求 d3.js 的行并单击它,然后单击响应标签。看看你做了什么,因为这可以说明很多问题。

编辑#2:也可能是script(scr="") 中的错字:)

【讨论】:

  • 嗨,在上面添加了我的文件结构的图片,以及我的一个网络选项卡...看起来没有尝试加载它?
  • @zbnrg in graph.js 你在使用res.render('graph')吗?然后你编辑了哈巴狗页面并刷新了它,你仍然在网络选项卡中得到它?您的控制台选项卡中是否出现错误? (只是排除了简单的解决方案)
  • 对,这就是我点击刷新时的样子,我得到的唯一错误是在 barchart.js 中调用时未定义 d3。
  • 这可能只是粘贴,但是那些脚本标签是否正确缩进在你的哈巴狗的 body 标签下?
  • 是的,哈,我在粘贴时遇到了一些麻烦,在我的 pug 文件中,它们与 body 标签对齐
猜你喜欢
  • 1970-01-01
  • 2015-10-27
  • 2020-02-04
  • 1970-01-01
  • 1970-01-01
  • 2019-05-07
  • 2020-11-21
  • 2018-07-21
  • 2021-09-24
相关资源
最近更新 更多