我在 cloud9 IDE 中进行了以下设置。
项目根文件夹
- Hello.html - 包含简单的 html 标签(+图像标签)预览显示图像
- HelloHtml.js - 读取 html 文件并写入客户端(响应)的 Node js 文件。 .
- Penguins.jpg - 同一文件夹中的图像文件。
当我运行服务并在浏览器中点击 URL 时,HTML 将呈现为“Hello World!”显示为 .但图像没有得到渲染。 img 标签中的 src=""属性应该是什么。
图像文件的路径应该是什么?谢谢。
HelloHtml.js
var http = require('http');
var fs = require('fs');
http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./Hello.html', function(err, data){
if(err) throw err;
response.end(data);
});
}).listen(process.env.PORT);
console.log('Hello World HTML Service has started.');
Hello.html
<html>
<head>
<title>Node JS</title>
</head>
<body>
<h2>Hello world!</h2>
<img src="Penguins.jpg" />
</body>
</html>
最佳答案
您没有处理代码中任何位置的静态文件,无论如何,您只是提供文件“hello.html”:
http.createServer(function(request, response) {
response.writeHead(200, {
'Content-Type': 'text/html'
});
fs.readFile('./Hello.html', function(err, data){
if(err) throw err;
response.end(data);
});
}).listen(process.env.PORT);
要么根据请求 URL 制定路由方案,要么使用此处的一些静态文件服务器:
https://github.com/joyent/node/wiki/modules#wiki-web-frameworks-static
我建议你看看 Express,它也有这个功能和路由处理:expressjs.com
关于html - 云9 : nodejs server image not getting rendered (HTML),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8504290/