Stijn
Stijn

Reputation: 305

Node.js won't send CSS in response

I'am trying to set up a client/server program with node.js. I have the following code, which returns a .html file when connected.

JavaScript:

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

fs.readFile('./FrontPage.html', function (err, html){
if (err){
    throw err;
}

server = http.createServer(function (req, res) {
    res.writeHead(200, {
        "Content-Type": "text/html"
    });
    res.write(html);
    res.end();
    console.log("HTTP response sent");
});

var port = 3000;
server.listen(port, function () {
    console.log("Server listening on port " + port);
}); 
});

HTML:

<head>
    <link rel="stylesheet" type="text/css" href="./css/FrontPageCSS.css">
</head>



<body style="background-image:url(./img/bg.jpg)">

<div id="header">
        <a href="./frontPage.html"><img src="./img/Logo.png" height="5%" width="5%" alt="logo"></a>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
        <script src="./script/FrontPageJS.js"></script>
</div>

<div id="buttonWrapper">
    <div id="first" class="first">
        This is my first button
    </div>

    <div id="second" class="second">
        This is my second button
    </div>
</div>

When I access localhost on port 3000 in my browser, it returns the .html file without the CSS. When I open the .html individually via it's path, the CSS works just fine.

My question: Why is the CSS not included in the response and how can I include it?

Upvotes: 0

Views: 1098

Answers (1)

alberto-bottarini
alberto-bottarini

Reputation: 1231

CSS files are not included in HTML. They are downloaded by the browsers during HTML parsing.

Your example doesn't work because, when browser tries to get css/FrontPageCSS.css it obtains the HTML output because your server responds always with content of FrontPage.html file.

I suggest you to use some web framework as express: http://expressjs.com/en/index.html

Upvotes: 2

Related Questions