0

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?

1
  • 1
    because... assets like that don't get returned in the same response as the .html file, they get returned separately as the browser requests them. I see nothing in your node.js that would serve the .css file. Commented Dec 3, 2015 at 16:24

1 Answer 1

2

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

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

3 Comments

To add: especially look at hosting static files through express. From the horse's mouth: expressjs.com/en/starter/static-files.html
I didn't downvote, but your answer can be read to suggest that Express takes care of hosting static files out of the box. That is not the case. Instead consider adding a more specific link next time.
Man, you was so rude with me :)

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.