Reputation: 163
I am currently serving my HTML page which references style.css and index.js, however, these files are not being applied to the HTML page even though I explicitly stated to include them if they are requested by 'req'?
My HTML (to show inclusions):
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test site</title>
<link rel="stylesheet" href="/style.css" media="screen">
<script src="/index.js" charset="utf-8" defer></script>
.
.
.
My server.js code:
var PORT = 3000;
var http = require('http');
var fs = require('fs');
var path = require('path');
//cache the files
var index = fs.readFileSync('public/index.html', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
var style = fs.readFileSync('public/style.css', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
var indexJS = fs.readFileSync('public/index.js', 'utf8', function read(err, data) {
if (err) {
throw err;
}
});
function requestHandler(req, res){
res.setHeader('Content-Type', 'text/html');
res.statusCode = 200
res.write(index);
if(req.url === '/style.css'){
res.write(style);
}
if(req.url === '/index.js'){
res.write(indexJS);
}
res.end();
}
//use 3000 by default if PORT is not defined
if(!(typeof PORT !== 'undefined') || PORT === null){
http.createServer(requestHandler).listen(PORT);
}
else{
http.createServer(requestHandler).listen(3000);
}
Upvotes: 0
Views: 647
Reputation: 71
Looks like you have the right idea but there are a couple things to note in the server code.
Setting the Content Type
header tells the web browser how to interpret the file it is receiving. Your server code always sets it to 'text/html' where it should be set to 'text/css' for css, and 'text/javascript' for your js files.
res.write
will append the file contents to the response. Since res.write(index)
is being executed on every request, your HTML is being sent before the css/js within the same file. Try using a conditional for HTML like you are doing for CSS/JS like
if(req.url === '/') {
res.setHeader('Content-Type', 'text/html');
res.write(index);
}
Upvotes: 2