Error: d3 is not defined

1,563 views
Skip to first unread message

Adnan Salahuddin

unread,
Mar 29, 2018, 6:42:57 AM3/29/18
to d3-js
Hi folks,

I am using node.js server and d3 library. Here is my sample code as below:

Index.html:
<!DOCTYPE html>
<html>
<head>
    <!-- <script src="https://d3js.org/d3.v4.min.js"></script>  -->
    <script src="./d3/d3.min.js"></script>
</head>
<body>
    <script>
      d3.select("body")
        .append("h1")
        .text("hello world!");
    </script>
</body>
</html>

app.js
var http = require('http');
var fs = require('fs');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/html'});
  fs.readFile('index.html', function(error, data) {
      if(error){
          response.writeHead(404);
          response.write('File not found');
      }else{
        response.write(data);
      }
      response.end();
  });
}).listen(8080);


I run node app.js and i am getting error message and it says:

How to fix it? 
I am waiting for your response. 

Thanks in Advance 

Curran

unread,
Mar 29, 2018, 9:49:47 AM3/29/18
to d3-js
Greetings,

Your code is requesting "./d3/d3.min.js". So, if you access http://localhost:8080/index.html, that page will try to fetch http://localhost:8080/d3/d3.min.js. From looking at your server code, that request will not return the D3 code, it will return the contents of index.html (as all requests will). That is your issue.

If you navigate to http://localhost:8080/d3/d3.min.js, the d3 code should show up. To achieve this, you can use Express to create your Node.js server, and serve static files using the static middleware - see https://expressjs.com/en/starter/static-files.html .

Best regards,
Curran

Adnan Salahuddin

unread,
Mar 30, 2018, 3:04:31 AM3/30/18
to d3-js
Problem has been solved.
Thank you so much
Reply all
Reply to author
Forward
0 new messages