2

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.

4
  • What if you use a valid HTML page (with a doctype and everything) and write type="text/javascript" on the script tag Commented Jan 29, 2014 at 16:15
  • Hmm... Isn't it complaining about Chart.js, line #1? Commented Jan 29, 2014 at 16:18
  • Try to access http://localhost/Chart.js/Chart.js, you should see that your server always serves the same page for each request, without taking into account the path. Commented Jan 30, 2014 at 9:37
  • Paul you're rigth, I'm a novice with node.js and didn't thought about that. I will handle the request url, thank you for your help. Commented Jan 30, 2014 at 11:01

1 Answer 1

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:

Sign up to request clarification or add additional context in comments.

1 Comment

Yes as Paul said in the comment I didn't handle the request url. Thank you for helping !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.