I am new to node and am trying to get simple css file to load upon starting a simple node app. Thing is, css does load when I simply open index.html directly in a browser.
Project structure:
├── node
│ └── app
│ ├── app.js
│ ├── index.html
│ ├── server.js
│ └── styles
│ └── style.css
I can open style.css by clicking on the href in the html file, so why doesn't it load when I call localhost:8080?
The Response tab shows the html file, so that seems off. Should it show that?
app.js
var http = require('http');
var fs = require('fs');
const PORT=8080;
fs.readFile('./app/index.html', function (err, html) {
if (err) throw err;
http.createServer(function(request, response) {
response.writeHeader(200, {"Content-Type": "text/html"});
response.write(html);
response.end();
}).listen(PORT);
});
style.css
. {
box-sizing: border box;
}
html, body {
height: 100%;
width: 100%;
}
body {
margin: 0;
border: 5px solid blue;
}
#container {
margin: 3% 10% 0 5%;
border: 2px solid #dddddd;
}
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" type="text/css" href="styles/style.css">
</head>
<body>
<div id="container">
<div>
<h1 class="title">Title</h1>
</div>
</div>
</body>
</html>
The server is now sending a single file, but you need to read and send every requested file, i.e. you need to serve static files.
To do that, you can check requested URL and read the file, as explained here:
https://nodejs.org/en/knowledge/HTTP/servers/how-to-serve-static-files/
Also check different solutions for serving static files:
Try this, it will log every requested file to the console. Furthermore, to get index.html to serve, you'd need to type in http://localhost:8080/index.html. To avoid that, we can catch the / route, and send that file on that route, so http://localhost:8080 will serve index.html, so we have a bit of routing too.
var fs = require('fs'),
http = require('http');
http.createServer(function(req, res) {
let file = req.url;
// serve index.html on http://localhost:8080/
if (file === '/') {
file = '/index.html';
}
console.log('serving static file: ', file);
// read every requested file, and send it to the browser
fs.readFile(__dirname + file, function(err, data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return;
}
res.writeHead(200);
res.end(data);
});
}).listen(8080);
However, you can notice that the example doesn't write content-type header, so you'd need to check every request, detect mime type and add the header, which requires extra code, and which is why it's better to use libraries that do that out of the box.