Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
328 views
in Technique[技术] by (71.8m points)

javascript - 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 odejsdefault.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
        });
        res.write(data);
        res.end();
    });
}).listen(1337, '127.0.0.1');
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your server:

http.createServer(function (req, res){
   fs.readFile('index.html'

… 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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...