Michael Tot Korsgaard
Michael Tot Korsgaard

Reputation: 4014

NodeJS can't load css file

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".

Upvotes: 3

Views: 1591

Answers (1)

Magus
Magus

Reputation: 15104

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.

Upvotes: 4

Related Questions