Reputation: 788
I have the following basic script running in nodejs to serve up an html file with an associated css stylesheet:
var http = require('http');
var fs = require('fs');
var path = require('path');
var serverPort = 8080;
var server = http.createServer(function(request, response) {
console.log('request starting ...');
var extname = path.extname(request.url);
var contentType = 'text/html';
switch (extname) {
case '.js':
contentType = 'text/javascript';
break;
case '.css':
contentType = 'text/css';
break;
}
fs.readFile('js/EmailDisplay/htm/index.html', function(error, content) {
if (error) {
console.log(error);
response.writeHead(500);
response.end();
} else {
console.log(contentType);
response.writeHead(200, {'Content-Type': contentType});
response.end(content,'utf-8');
}
});
});
server.listen(serverPort);
console.log('Server running at localhost:' + serverPort +"/");
If I open the file in Firefox (File->Open File), it renders properly. If I go to localhost:8080 the index page is served but without the style applied to it. Why? The console.log in the fs.readFile block shows me that both files are being read.
PS - I know there are packages that will let me do this blindly (eg. 'connect') but I'm trying to understand what is actually happening before going that route.
Upvotes: 2
Views: 1938
Reputation: 17089
I ran into this same issue with nodejs and express. See my sample server.js
below
var express= require("express");
var app= express();
app.get("/", function(request, response) {
response.sendFile("testing.html", {root: "."});
});
app.listen(8080);
Static content can be added by including the line:
app.use(express.static("foundation-5.4.6", {index: false}));
This uses express.static. In my case, I'm serving static css and js from the Foundation framework, but you can easily modify this to your specific public
folder.
Upvotes: 0
Reputation: 36767
The problem lies probably in this line:
fs.readFile('js/EmailDisplay/htm/index.html', function(error, content) {
You're reading and returning to the client the same html file, even when .js
and .css
are requested.
You should probably set the path to the file along its content type in the switch you have earlier in your code.
Upvotes: 2