Reputation: 317
I'm not sure why the CSS is being ignored here. Is there something specific I need to do with NodeJS in order to be able to use CSS inside HTML? Has it got anything to do with the tag's "type" attribute?
The NodeJS code:
app.get('/', function(request, response){
response.sendFile('/home/ubuntu/index.html');
});
HTML code (index.html):
....
<link href="styles.css" rel="stylesheet" type="text/css" />
....
Upvotes: 1
Views: 990
Reputation: 1
After going through this problem, my solution to this is as follows.
http.createServer(function(req, res) {
if (req.url === '/') {
fs.readFile('menu.html', function (err, data) {
if (err) throw err;
res.writeHeader(200, {"Content-Type": "text/html"});
res.write(data);
res.end();
});
}
else if (req.url === '/menu.css') {
fs.readFile('menu.css', function(err, data) {
if (err) throw err;
res.writeHead(200, {'Content-Type': 'text/css'});
res.write(data);
res.end();
});
}
}).listen(PORT);
It was very tough for me as a beginner to understand how to debug this problem. But using console.log(req.url) I was able to figure out this issue of serving css.
it seems that here we are addressing each request separately
Upvotes: 0
Reputation: 943537
Your Node.js code says:
When the browser requests /
send a copy of the file index.html
You don't have any code which handles the case:
When the browser requests /styles.css
.
You need to deal with that case (probably by writing something generic that matches arbitrary requests against your filesystem, which you might do by looking for a static hosting library — for example by using the express framework and its static module).
That said, if you are just going to serve static files, then you might as well not use Node at all and use a general webserver.
Upvotes: 2