我跟隨Bucky新波士頓的教程,似乎無法讓圖像顯示在節點中運行簡單靜態索引頁的HTML文件中。 jsnode.js簡單的HTTP服務器,內容html不顯示圖像
請注意:這是一個學校項目,我負責這樣做而不使用我們尚未達成的express或connect等中間件。 :d
var http = require('http');
var fs = require('fs');
var accessTime = new Date();
var accessCount = 0;
function send404Response(response) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("Error 404: Page not found!");
response.end();
}
function onRequest(request, response) {
if (request.method == 'GET' && request.url == '/'){
response.writeHead(200, {"Content-Type": "text/html"});
fs.createReadStream("./index.html").pipe(response);
fs.writeFileSync("logfile.txt", "\n Someone has accessed the index page \n" + accessTime + "\n ", "UTF-8",{'flags': 'a'});
console.log("A user made a request");
accessCount += 1;
console.log(accessCount + " page requests so far . . .");
}else {
send404Response(response);
}
}
http.createServer(onRequest).listen(8888);
console.log("Server is running...");
當我運行它,在HTML頁面加載罰款爲localhost:8888,但沒有圖像會顯示出來,除非我使用外部圖像。例如,HTML只會有標準的圖像標籤?
<img src='photo.jpg' .... /> // doesnt work
<img src='http://www.AWebSite.com/photo.jpg' .... /> // naturally works
謝謝!!
再看看你的'onRequest'函數,並檢查請求是什麼樣的。做一個'console.log(request)'。你會看到有幾個請求,只有一個滿足'如果陳述'... –