无法使用nodeJS在html中设置Image src

Unable to set Image src in html using nodeJS

本文关键字:设置 Image src html nodeJS      更新时间:2023-09-26

我是nodeJS的新手,无法在客户端html中设置img标记的src。因为我的节点服务器正在端口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" />