我是 nodeJS 的新手,我无法在我的客户端 html 中设置 img 标签的 src。 因为我的 Node 服务器在端口 3000 上运行。当我点击 http://localhost:3000 时它工作正常,
下面是我的server.js文件的代码
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
app.get('/', function (req, res) {
res.sendFile('/var/www/UI-Test/client.html');
});
io.on('connection', function (socket) {
console.log('user joined ');
});
http.listen(3000, function () {
console.log('listening on *:3000');
});
下面还有client.html的代码
<html>
<body>
<img src="f1.png" /> <!-- also tried "./f1.png" -->
<script>
var socket = io();
</script>
</body>
</html>
即使 f1.png 文件与 server.js 和 client.html 位于同一文件夹中,也会出现 404(未找到)错误。顺便说一句,我的操作系统是 ubuntu。
提前致谢
最佳答案
// At the top of your server.js
process.env.PWD = process.cwd()
// Then
app.use(express.static(process.env.PWD + '/public'));
并将您的图像存储在 /public/f1.png
在html部分调用
<img src="/f1.png" />
关于javascript - 无法使用nodeJS在html中设置Image src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29536739/