Frage

I am trying to use Chart.js with node.js. I downloaded Chart.js from the following git source: https://github.com/nnnick/Chart.js and tested it with php and things worked fine.

Now I am working with node.js but I have an issue:

Resource interpreted as Script but transferred with MIME type text/html: "url/Chart.js/Chart.js" localhost/:3 Uncaught SyntaxError: Unexpected token < /Chart.js/Chart.js:1

debug.html

<html><head>
  <script src="Chart.js/Chart.js"></script>
</head></html>

index.js

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

var fichier=fs.readFileSync('debug.html', 'utf-8');

var server = http.createServer(function(req,res){
    res.writeHead(200, {'Content-Type': 'text/html'});

    res.write(fichier);

    res.end();
});
server.listen(80);

I know that the path is good, node can find it so what is the problem?

Thank you for helping.

War es hilfreich?

Lösung

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:

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top