Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
189 views
in Technique[技术] by (71.8m points)

javascript - CSS and JS not loading on Node.js server

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...