1

I have external css file used by the html page in my nodeJS project. Following is my file structure

ProjectFolder  
----server.js  
----index.html  
----style.css

My server.js file is following

var http = require('http');
var fs = require('fs');
var $ = require('jquery');

function onRequest(request, response) {
 response.writeHead(200,{'Content-Type':'text/html'});
 fs.readFile('./index.html',null, function (error,data) {
    if(error){
        response.writeHead(404);
        response.write('File not found')
    } else {
        response.write(data);
    }
    response.end();
 });
}

http.createServer(onRequest).listen(8081);

My html page is following

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href='style.css'>
<script src="https://ajax..."></script>
<script>
   ........ 
</script>

</head>
<body>
<div id="inputDiv">
<h1>User Details</h1>
</div>
</body>
</html>

My css file is following

div {padding-bottom: 10px}
label {float: left; width: 6em; text-align: right;padding-right: 4px}
input {text-align: left;}
textarea {alignment: right;}

When I run node server.js and access index.html, it loads the html page without css styling. But I tried opening my html page outside nodejs (just in the browser) and then I can see styles. What is the issue in my code?

1
  • 1
    Refer to this link, it might help you Commented Apr 27, 2018 at 9:48

1 Answer 1

1

Your web server does not serve the CSS file. Try to access it manually. It won't work.

When you run your file from filesystem file:///, the style.css can be loaded because it is in the same directory.

But when you use something like localhost/index.html or something, the browser tries to access localhost/style.css but the nodejs server you have above would not handle the file.

See this answer which might be a help for you.

If you want to make a practical web server use something like Express or Koa.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.