代碼:
html:
<img src="./public/a.jpg">
Nodejs:
var http = require('http');
http.createServer(function (req, res) {
//獲取文件類型
var type = req.url.substr(req.url.length - 4, req.url.length);
//獲取資源路徑
var realpath = __dirname + '/public/';
//加載需要顯示的圖片資源
if (type == '.jpg') {
res.writeHead(200, { 'Content-Type': 'text/'+type });
res.end(fs.readFileSync(realpath + 'a.jpg'));
}
//加載靜態html文件
if (req.url == "/") {
res.writeHead(200, { 'Content-Type': 'text/html' });
res.end(fs.readFileSync(__dirname + '/index.html'));
}
}).listen(8080, function () {
console.log("http://localhost:8080");
});
這樣加載的html文件中的圖片就能夠顯示了