Search code examples
javascriptnode.jsd3.jslocalserver

D3.json Unexpected token with Node.js Server


trying to learn D3 I wrote the following local server:

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

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

}

http.createServer(onRequest).listen(8000, '127.0.0.1');

I then go to http://127.0.0.1:8000/ to render this index.html:

<html>
<body>
<script src="https://d3js.org/d3.v5.min.js"></script>
<script>

    var stringit = `[{"coin_val": 4999999,"coin_lab": "#PAX"},{"coin_val": 1100000,"coin_lab": "#USDC"}]`;

    console.log('working.')

    d3.json('./data.json', function(err, data) {
        console.log(err)
        console.log(data)
    });
</script>

</body>
</html>

but I receive the following error in Chrome console:

Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 1 at Go (d3.v5.min.js:2) Go @ d3.v5.min.js:2

What am I doing wrong? is it i the 3D code or I just don't get the server right? how can I get D3 to read a JSON file in a Node.js server?

I suspect the JSON is not the issue, something goes wrong on the server side and reads the HTML in a wrong way?


Solution

  • I wrote the following local server

    Which serves up the contents of index.html in response to any request it gets.

    d3.json('./data.json',

    So your JavaScript asks for data.json and it gets the contents of index.html.

    Since the contents of index.html are not JSON, and start with a <, it throws the error message. A JSON file cannot start with a <.

    You need to fix your server so it gives the browser what it asks for instead of blindly sending index.html.