我正在嘗試通過 http.createServer() 的回呼加載一個 HTML 頁面以及兩個單獨的 CSS 檔案。到目前為止,這是代碼的重要部分:
var server = http.createServer(function (req, res) {
var htmlData = fs.readFileSync(__dirname "/public/index.html");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(htmlData);
res.end();
}).listen(port);
當我嘗試加載它時,它還會嘗試加載 HTML 檔案中鏈接的 CSS 檔案。我已經嘗試在標題中添加直接鏈接并在 HTML 檔案中添加腳本以將鏈接添加到標題中,但都不起作用。如何在不將 CSS 檔案的內容直接放在 HTML 檔案的標簽中的情況下執行此操作?
uj5u.com熱心網友回復:
您忽略了請求路徑并每次都給它相同的檔案。
您需要根據請求提供正確的檔案。
例如:如果您想提供兩個檔案,index.html并且style.css:
var server = http.createServer(function (req, res) {
if (req.url === '/' || req.url === '/index.html') { // respond to both / and /index.html
var htmlData = fs.readFileSync(__dirname "/public/index.html");
res.writeHead(200, { 'Content-Type': 'text/html' });
res.write(htmlData);
res.end();
}
else if (req.url === '/style.css') { // respond to /style.css
var cssData = fs.readFileSync(__dirname "/public/style.css");
res.writeHead(200, { 'Content-Type': 'text/css' });
res.write(cssData);
res.end();
}
}).listen(port);
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/367186.html
標籤:javascript html css 节点.js http
