I am currently in the process of learning Node.js, but I have encountered a small issue with retrieving data from a css file. Interestingly, when I directly add the data to the index file's code, it seems to work perfectly.
Let me share the relevant snippets of my code:
app.js
var http = require('http');
var fs = require('fs');
//404 response
function send404response(response) {
response.writeHead(404, {
"Context-Type": "text/plain"
});
response.write("Error 404: Page not found!");
response.end();
}
function onRequest(request, response) {
if (request.method == 'GET' && request.url == '/') {
response.writeHead(200, {
"Context-Type": "text/html"
});
fs.createReadStream("./index.html").pipe(response);
} else {
send404response(response);
}
}
http.createServer(onRequest).listen(8888);
console
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8>
<link rel="stylesheet" type="text/css" href="main.css" >
<title>First node app</title>
</head>
<body>
<div class="header"></div>
<div class="container">Welcome to my first website! <br> This website is created in NodeJs!</div>
</body>
</html>
main.css
* {
margin: 0px;
padding: 0px;
}
body {
background: url('https://i.sstatic.net/1voHP.png') repeat;
font-size: 100%;
}
.header {
width: 100%;
height: 500px;
background: rgba(0, 0, 0, .9);
}
.container {
font-size: 1em;
margin: 0 auto;
width: 70%;
height: 90%;
background: rgba(0, 0, 0, .3);
padding: 5%;
}
* {
margin: 0px;
padding: 0px;
}
body {
background: url('https://i.sstatic.net/1voHP.png') repeat;
font-size: 100%;
}
.header {
width: 100%;
height: 500px;
background: rgba(0, 0, 0, .9);
}
.container {
font-size: 1em;
margin: 0 auto;
width: 70%;
height: 90%;
background: rgba(0, 0, 0, .3);
padding: 5%;
}
All these files are stored in the same directory.