D3.json Node.js 服务器的意外令牌

D3.json Unexpected token with Node.js Server

尝试学习 D3 我编写了以下本地服务器:

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');

然后我去 http://127.0.0.1:8000/ 渲染这个 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>

但我在 Chrome 控制台中收到以下错误:

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

我做错了什么?是我的 3D 代码还是我没有正确设置服务器?如何让 D3 读取 Node.js 服务器中的 JSON 文件?

我怀疑 JSON 不是问题所在,服务器端出现问题并以错误的方式读取 HTML?

I wrote the following local server

它提供 index.html 的内容以响应它收到的任何请求。

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

因此您的 JavaScript 请求 data.json 并获得 index.html.

的内容

由于 index.html 的内容不是 JSON,并且以 < 开头,因此会抛出错误消息。 JSON 文件不能以 <.

开头

您需要修复您的服务器,以便它向浏览器提供它所要求的内容,而不是盲目地发送 index.html

您的问题似乎是您的代码除了 index.html 之外不知道如何提供任何服务。使用纯节点服务器真的很令人沮丧,因为互联网上的大多数资源都假定用户将使用 express 或其他框架。

下面我有一个服务器,可以为静态网站提供服务并处理对几种常见媒体类型的请求。您可以通过查找该文件格式的 MIME 类型修改 getContentType 函数中的代码来添加其他类型。

希望对您有所帮助

'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);
})();