簡體   English   中英

CSS 和 JS 未加載到 Node.js 服務器上

[英]CSS and JS not loading on Node.js server

我剛剛開始學習 Node.js,我寫了這樣一個最簡單的服務器:

 // 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>

和服務器:

 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'); }); })

我的問題是我第一次運行這段代碼時效果很好 - css 和 js 加載沒有問題。 但后來我同時在同一台服務器上試驗 PHP 和 Node.js(使用 nginx)。 我失敗了,因為我不需要太多(只是為了好玩)我放棄並更改了所有更改以實現此目標設置(例如 nginx-conf 中的端口)。 然后,在嘗試再次運行此代碼后,它不會加載 sheet1.css 和 main.js。 為什么會這樣? 我把所有設置都恢復到默認狀態了嗎?

感謝您的回答。

這是您的服務器邏輯:

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

瀏覽器請求/ ,服務器給它html變量的值。

瀏覽器請求/sheet1.css ,服務器給它html變量的值。

瀏覽器請求/main.js ,服務器給它html變量的值。


需要注意req對象中的URL,給瀏覽器它要求的東西,而不是不管要求什么就盲目發送html

請注意,您還需要設置正確的Content-Type響應標頭。

(您可能還應該避免重新發明輪子並使用專為此設計的Express.js及其靜態模塊)。


我的問題是我第一次運行這段代碼時效果很好 - css 和 js 加載沒有問題。

這不可能發生。 可能您從file: URL 加載了index.html並完全繞過了服務器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM