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

Categories

I've just started to learn Node.js and I wrote the easiest server like this:

// workspace

const p = document.querySelector('p');
p.textContent = 'aleluja';
html {
font-size: 10px;
}

body {
font-size: 2rem;
}
<!DOCTYPE html>
<html lang="pl">
<head>

<meta charset="utf-8">

<title>Go go go</title>

<link href="sheet1.css" rel="stylesheet">

<script src="main.js" async></script>

</head>
<body>

<p>something</p>

</body>
</html>
See Question&Answers more detail:os

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

1 Answer

This is your server logic:

   const server = http.createServer((req, res) => {
     res.statusCode = 200;
     res.setHeader('Content-type', 'text/html');
     res.write(html);
     res.end();
   });

The browser asks for /, the server gives it the value of the html variable.

The browser asks for /sheet1.css, the server gives it the value of the html variable.

The browser asks for /main.js, the server gives it the value of the html variable.


You need to pay attention to the URL in the req object and give the browser what it asks for instead of blindly sending html no matter what is asked for.

Note that you will also need to set the correct Content-Type response header.

(You should probably also avoid reinventing the wheel and use Express.js and its static module which are designed for this).


My problem is that first time I run this code it worked fine - css and js loaded without problems.

There is no way that could have happened. Possibly you loaded index.html from a file: URL and bypassed the server entirely.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...