Skip to content Skip to sidebar Skip to footer

Style And Javascript Files Not Applied To Page That Is Serving Html In Node.js

I am currently serving my HTML page which references style.css and index.js, however, these files are not being applied to the HTML page even though I explicitly stated to include

Solution 1:

Looks like you have the right idea but there are a couple things to note in the server code.

Setting the Content Type header tells the web browser how to interpret the file it is receiving. Your server code always sets it to 'text/html' where it should be set to 'text/css' for css, and 'text/javascript' for your js files.

res.write will append the file contents to the response. Since res.write(index) is being executed on every request, your HTML is being sent before the css/js within the same file. Try using a conditional for HTML like you are doing for CSS/JS like

if(req.url === '/') {
  res.setHeader('Content-Type', 'text/html');
  res.write(index);
}

Post a Comment for "Style And Javascript Files Not Applied To Page That Is Serving Html In Node.js"