首页 > 解决方案 > External CSS is not working in NodeJS

问题描述

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?

标签: htmlcssnode.js

解决方案


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.


推荐阅读