简体   繁体   中英

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>

And the server:

 const http = require('http'); const fs = require('fs'); const hostname = '127.0.0.1'; const port = 3000; fs.readFile('index.html', (err, html) => { if (err) { throw err; } const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-type', 'text/html'); res.write(html); res.end(); }); server.listen(port, hostname, () => { console.log('started'); }); })

My problem is that first time I run this code it worked fine - css and js loaded without problems. But later I was experimenting with PHP and Node.js on the same server at once (using nginx). I failed and because I didn't need it too much (it was just for fun) I gived up and changed all changed to achieve this goal settings (like ports in nginx-conf). And then, after trying to run this code again, it doesn't load sheet1.css and main.js. Why is it so? I turned though all settings back to their default state?

Thanks for your 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM