[Chartjs]-Chartjs with Node.js : Unexpected token <

1👍

Your HTTP server doesn’t look at the requested URL and always sends back the same page:

$ curl http://localhost/
<html><head>
  <script src="Chart.js/Chart.js"></script>
</head></html>

$ curl http://localhost/Chart.js/Chart.js
<html><head>
  <script src="Chart.js/Chart.js"></script>
</head></html>

$ curl http://localhost/random/url
<html><head>
  <script src="Chart.js/Chart.js"></script>
</head></html>

The solution is then to look at req.url and serve the correct file:

var server = http.createServer(function(req,res){
    if (req.url === 'Chart.js/Chart.js') {
        res.writeHead(200, {'Content-Type': 'application/javascript'});
        fs.createReadStream('./Chart.js/Chart.js').pipe(res);
        return;
    }
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.write(fichier);
    res.end();
});

Note that this code snippet isn’t a generic solution at all, and will not fit your needs nor will it scale easily to multiple files. You can look at some projects to have a better understanding of the solutions:

Leave a comment