Style sheet - not loading with web page

I'm running a local copy of nodejs and have taken some code which runs a web service and references a local index.html on startup. This service is running locally on my desktop.

I've been playing about with CSS, and have found no matter what I do, the style sheet does not load, taking the configuration from the style sheet and dropping this within some <style> elements works fine. But for some reason or another, it's not reading the stylesheet.

Location of style sheet is: c:\program files\nodejs\default.css

HTML code:

<link rel="stylesheet" type="text/css" href="default.css" />

This is in the same location as index.js, index.html. Has permissions etc to read file.

Any ideas why this potentially may not be loading.

index.js code:

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

http.createServer(function (req, res){    
    fs.readFile('index.html', function (err, data){
        res.writeHead(200, {
                    'Content-Type': 'text/html',
                    'Content-Length' : data.length
}).listen(1337, '');



Your server:

http.createServer(function (req, res){

… is configured to ignore everything in the request and always return the contents of index.html.

So when the browser requests the stylesheet it is given index.html.

You need to pay attention to the path (which will be in the request) and serve up appropriate content (which for serving up static files means mapping it onto the file system, determining if the file exists or not, then loading that file or a 404 message), with the appropriate content type (so you'd need to determine that for each kind of file), and status code.

This is a significant chunk of work and not worth reinventing the wheel over so it would probably be best done by finding a static file serving module (Google turns up node-static) for Node (or replacing Node with something like Lighttpd or Apache HTTPD).

If you want to serve up dynamic content as well as static content, then Express is a popular choice (and has support for static files).


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.