2017-10-06 94 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); 
相关问题