当我尝试使用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 :(得分: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);