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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…