1

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" />
....
1
  • You need to serve your CSS also, or embed it in the HTML. Commented Feb 17, 2016 at 0:02

2 Answers 2

2

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.

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

Comments

0

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

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.