0

In my local NodeJS app file I'm trying to load HTML file with CSS link using jsdom module and then display it on the browser this way

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

http.createServer(function(req, res) {

    if (req.url === '/favicon.ico') {
        res.writeHead(404);
        res.end();
        return;
    }

    res.writeHead(200, {'Content-Type': 'text/html; charset=utf8'});

    var indexPageHTML = fs.readFileSync('index.html');
    var document = new jsdom.JSDOM(indexPageHTML,{resources: "usable"}).window.document;
    var indexPageHTML = '<!doctype html><html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>';

    res.end(indexPageHTML);

}).listen(80, 'localhost');

My index.html

<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
Some text
</body>
</html>

But the CSS still isn't loaded and I still get the warning

Resource interpreted as Stylesheet but transferred with MIME type text/html: "http://localhost/style.css".

How should the resources: "usable" option work? Which is mentioned by the link https://www.npmjs.com/package/jsdom#basic-options

3
  • I think the problem is that you are writing head 'Content-Type': 'text/html;. And as node is backend it needs headers to get the text/css headers as well. Currently its thinking css file as html file. Try to add res.writeHead(200, {'Content-Type': 'text/css; charset=utf8'}); Commented Oct 31, 2018 at 16:15
  • @CreativeDip it was not me who down-voted your answer. So there is no reason to down-vote my question Commented Oct 31, 2018 at 16:21
  • I didn't downvote your question. Somebody else did, i feel that my answer is wrong so i removed it. Commented Oct 31, 2018 at 16:21

2 Answers 2

0

It's just because of your http server returns 404 error for /favicon url and same html page for every other request. When you page loaded at first time in the browser, your browser parse <link rel="stylesheet" href="style.css"> tag and send another request to your server. But your server returns same html page again, instead of styles.

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

Comments

0

It's better to install the serve-static module

And if we want to get the page with the same name as request url (for example get another.html when click by the link with href="/another") it's enough to add

if(req.url != '/' && !~req.url.indexOf('.')) {
    req.url = req.url+'.html';
}

before the line

serve(req, res);

Comments

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.