user3127242 user3127242 - 5 months ago 20
CSS Question

Linking css files to node.js server

So I have craeted a node.js server with two routes. I use the fs to get the html files from the views folder and then append them to the page. In those html files I have a normal link to the css file, which does not seem to work. Here is my node.js app:

var port = 1357;

var http = require('http'),
path = require('path'),
mime = require('mime'),
fs = require('fs');

var app = http.createServer( function(req, res) {

if (req.url === '/home') {
fs.readFile('views/index.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}

else if (req.url === '/about') {
fs.readFile('views/about.html', function(err, page) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(page);
res.end();
});
}

else {
res.writeHead(301,
{Location: '/home'}
);
res.end();
}
});



app.listen(port);
console.log('Server running on port: ' + port)


In the html files I have:

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


It does not work. In chrome's console I get "Resource interpreted as Stylesheet but transferred with MIME type text/html. "

Answer

You defined 2 routes: /home and /about. You also defined that anything apart from these two routes should default to an HTTP redirect to the /home route, and this is what causes the problem.

When the browser encounters the link to the css file, it requests the following URL: /styles/styles.css. the server receives this URL and since it doesn't match the two defined routes it will go into the else statement which will send a redirect to /home, so your browser, asking for a css file, will only receive the html page located in /home.

To fix this, you might need to add a new rule for your css file:

else if (req.url === '/styles/styles.css') { fs.readFile('styles/styles.css', function(err, page) { res.writeHead(200, {'Content-Type': 'text/css'}); res.write(page); res.end(); }); }

Of course, if you have more css files you need to manage a specific folder instead of files. I suppose you're doing this to learn Node, because if you don't you might want to use express which is a Node ready to use web server that will save you lot of time.