3

So I'm trying to make a NodeJS server, and I try to keep as few add-ons as possible.

However, I have hit a problem, I don't seem to be able to load any CSS files called by my HTML files. The call do seem to be processed by the server, but it doesn't show in the browser.

My webserver.js file

// A very basic web server in node.js
// Stolen from: Node.js for Front-End Developers by Garann Means (p. 9-10) 

var port = 8000;
var serverUrl = "localhost";

var http = require("http");
var path = require("path"); 
var fs = require("fs");         

console.log("Starting web server at " + serverUrl + ":" + port);

http.createServer( function(req, res) {

    var now = new Date();

    var filename = req.url || "index.html";
    var ext = path.extname(filename);
    var localPath = __dirname;
    var validExtensions = {
        ".html" : "text/html",          
        ".js": "application/javascript", 
        ".css": "text/css",
        ".txt": "text/plain",
        ".jpg": "image/jpeg",
        ".gif": "image/gif",
        ".png": "image/png",
        ".ico": "image/png"
    };
    var isValidExt = validExtensions[ext];

    if (isValidExt) {
        localPath += filename;

        fs.exists(localPath, function(exists) {
            if(exists) {
                console.log("Serving file: " + localPath);
                getFile(localPath, res, ext);
            } else {
                console.log("File not found: " + localPath);

                if(ext === 'text/html'){
                    getFile(__dirname + '/404.html', res, ext);
                }
            }
        });

    } else {
         console.log("Invalid file extension detected: " + ext)
         getFile(__dirname + '/index.html', res, 'text/html');
    }

}).listen(port, serverUrl);

function getFile(localPath, res, mimeType) {
    fs.readFile(localPath, function(err, contents) {
        if(!err) {
            res.setHeader("Content-Length", contents.length);
            res.setHeader("Content-Type", mimeType);
            res.statusCode = 200;
            res.end(contents);
        } else {
            res.writeHead(500);
            res.end();
        }
    });
}


and the index.html

<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta charset="utf-8" />
        <link rel="stylesheet" type="text/css" href="style.css">
    </head>
    <body>
        <p>
            Hello
        </p>
    </body>
</html>


style.css

p{
    color: red;
}


server log

$ node webserver
Starting web server at localhost:8000
Serving file: c:\Users\MichaelTot\Desktop\Code Projects\Web\nodeJS/index.html
Serving file: c:\Users\MichaelTot\Desktop\Code Projects\Web\nodeJS/style.css


client log

Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://127.0.0.1:8000/style.css".
4
  • 1
    What does the log show? Commented Oct 22, 2015 at 12:25
  • Just added the log ^^ Commented Oct 22, 2015 at 12:27
  • 1
    Does http://127.0.0.1:8000/style.css contain the content you expect when you look at it? Commented Oct 22, 2015 at 12:30
  • try this res.setHeader("Content-Type", "text/html"); (also you might want to look into the express framework or hapi or something similar) Commented Oct 22, 2015 at 12:30

1 Answer 1

4

The problem is here :

getFile(localPath, res, ext);

You give ext to getFile, but according to the function signature, you are waiting for the mimetype. So you should do this :

getFile(localPath, res, validExtensions[ext]);

The browser don't read the css because by default NodeJS use the text/plain mimetype. But the browser wants a text/css mimetype for a css file.

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

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.