-1

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?

user3755529
  • 1,050
  • 1
  • 10
  • 30

2 Answers2

1

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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • ok that's quite difficult for me as I don't actually have knowledge of node.js servers. I can't find any guide either for Node.js serving D3. I guess it is not a good idea to use node.js to run D3 for beginner, maybe I should stick to python. – user3755529 Jan 27 '19 at 16:28
  • 2
    Maybe just install Apache HTTP, Lighttpd, Nginx, or some other common HTTP server instead of writing your own then. – Quentin Jan 27 '19 at 16:31
  • yes that's the answer I was looking for, I guess >python3 -m http.server< does the job too – user3755529 Jan 27 '19 at 16:35
0

your problem seems to be that your code doesn't know how to serve anything but index.html. It is really frustrating working with a pure node server because most resources on the internet assume that users are going to employ express or another framework.

Below I have a server that can serve static websites and handle requests for a few common types of media. You can add other types by modifying the code in the getContentType function by looking up the mime type for that file format.

I hope this helps

'use strict'


// Step 1: Declare Constants and Require External Resources

const port  = "8888", landing = 'index.html', hostname = "127.0.0.1";
const path  = require('path');
const http  = require('http');
const fs    = require('fs');
const qs    = require('querystring');


// Step 2: Create getContentType Function that Returns the Requested MimeType for the browser

/**
 * getContentType :: str -> str
 * 
 * Function returns the content type that matches the resource being
 *  requested by the server controller 
 */
function getContentType(url){

    const mimeTypes = {
        '.html' : 'text/html'               ,   '.js'   : 'text/javascript'                 ,
        '.css'  : 'text/css'                ,   '.json' : 'application/json'                ,
        '.png'  : 'image/png'               ,   '.jpg'  : 'image/jpg'                       ,
        '.gif'  : 'image/gif'               ,   '.svg'  : 'image/svg+xml'                   ,
        '.wav'  : 'audio/wav'               ,   '.mp4'  : 'video/mp4'                       ,
        '.woff' : 'application/font-woff'   ,   '.ttf'  : 'application/font-ttf'            ,
        '.otf'  : 'application/font-otf'    ,   '.eot'  : 'application/vnd.ms-fontobject'   ,
        '.wasm' : 'application/wasm'        
    };

    // If requested url extension is a mime type, the dict object will return that url's value, 
    //      otherwise octet-stream will be returned instead
    return mimeTypes[path.extname(url).toLowerCase()] || 'application/octet-stream';
}


// Step 3: Create sendFile Function that Delivers Requested files to the Response stream

/**
 * sendFile :: (str, str, str, stream) -> void
 * 
 * function delivers any requested resources to the stream
 */
function sendFile(file, url, contentType, request, response){
    fs.readFile(file, (error, content) => {
        if(error) {
            response.writeHead(404)
                    .write(`404 Error: '${url}' Was Not Found!`);

            response.end();
            // include file path for easy debugging, tabs added to make distinct
            console.log(`\t${request.method} Response: 404 Error, '${file}' Was Not Found!`);
        } else {
            response.writeHead(200, {'Content-Type': contentType})
                    .write(content);

            response.end();
            console.log(`\t${request.method} Response: 200, ${url} Served`);
        };
    });
};



// Step 4: Create serverController Function to initialize the server and run the request loop

/**
 * serverController :: str -> void
 * 
 * Function creates a server and accesses sendFile and getContentType to serve 
 *  requested resources 
 */
function serverController(hostname) {
    const server = http.createServer((request, response) => {

        // Creates space around .html requests so that they stand out more in the console
        if (path.extname(request.url) == '.html' || request.url == '/') {
            console.log(`\nPage Requested: ${request.url}\n`);
        } else {
            if (request.method == "GET") {
                console.log(`${request.method} Request: ${request.url}`);
            } else {
                console.log(`Request came: ${request.url}`);
            }
        }

        // Sends the requested resources to the response stream
        if (request.url == '/') {
            var file = path.join(__dirname, landing);       // delivers index.html by default
            sendFile(file, landing, 'text/html', request, response);
        } else {
            var file = path.join(__dirname, request.url);   // delivers requested resource
            sendFile(file, request.url, getContentType(request.url), request, response);
        };
    });

    // Gives server a port to listen to and gives an IP address to find it
    server.listen(port, hostname, () => {
        console.log(`Server running at ${hostname}:${port}\n`);
    });
}


// Step 6: Create launch IIFE Function that Starts the server upon Instantiation

(function launch() {
    serverController(hostname);
})();