2017-10-06 96 views
1

當我嘗試創建nodeJs服務器並使用html文件運行它時,它無法加載圖像。使用本地主機無法在NodeJS服務器上加載圖像

這是代碼的NodeJS:

var http = require('http'); 
var fs = require('fs'); 
fs.readFile('main.html', function (err, html) { 
    if (err) { 
     throw err; 
    } 
    http.createServer(function(request, response) { 
     response.writeHeader(200, {"Content-Type": "text/html"}); 
     response.write(html); 
    }).listen(8000); 
}); 

對HTML文件的主體的代碼是:

<body> 
<img id ="gug" src="./gugle.png"> 
<form> 
    <div id = "inp"> 
    <input type="text" id = "tb" placeholder="Search Results" value=""> 
    </div> 
    <span style=" margin-left: 420px"> <input type="submit" style = "height: 30px;width: 120px; font-family: Arial; font-weight: bold" onclick="alert_prompt('tb')" value="Google Search"> 
    <input type="button" style = "height: 30px;width: 120px; font-family: Arial; font-weight:bold" onclick= "lolfnc()" value = "I'm feeling lucky"> 
    </span> 
</form> 

<p style="margin-left: 370px; font-family: 'Times New Roman'"> 
    Google.co.in offered in:<span style="color: blue; font-size: small; font-family: SansSerif"> हिन्दी বাংলা తెలుగు मराठी தமிழ் ગુજરાતી ಕನ್ನಡ മലയാളം ਪੰਜਾਬੀ</span> 
</p> 
</body> 

和HTML文件也是在同一目錄。 任何幫助將不勝感激。

+0

你有沒有找到404圖像找不到錯誤? – kumbhanibhavesh

+0

如果你有錯誤,然後指定錯誤 –

+0

@ kumbhanibhavesh我沒有得到控制檯中的任何錯誤。當我只是在瀏覽器中運行html文件時,一切正常,但在nodeJs服務器中,腳本和css運行正常,但圖像沒有出現。 – Chanfool21

回答

0

您需要提供目錄中的所有資源,而不僅僅是html文件並指定MIME類型。有一個庫可以獲取mime類型的文件,稱爲mime,可以使用npm install進行安裝。或者,您可以僅使用您使用的幾種文件類型的開關盒。

const path = require('path') 
const http = require('http'); 
const fs = require('fs'); 
const mime = require('mime'); 

http.createServer(function(request, response) { 
    var filename = 'public'+request.url; 
    if (fs.existsSync('public'+request.url)) { 
     var fileExtension = path.extname(filename); 
     var mimeType = mime.getType(fileExtension); 
     response.writeHead(200, {"Content-Type": mimeType}); 
     var data = fs.readFileSync(filename); 
     response.end(data); 
    } else { 
     //404 not found error 
     response.writeHead(404, {"Content-Type": "text/html"}); 
     response.write("<h1>404 Not Found</h1>"); 
     response.end(); 
    } 
}).listen(80); 
相關問題