NodeJS res.sendFile 不发送图像或目录

NodeJS res.sendFile not sending images or directorys

本文关键字:图像 res sendFile NodeJS      更新时间:2023-09-26

所以如上所述,我只运行HTML文件,我能够看到图片,但是当我通过节点运行文件时,它会在我使用的文件上向我发送404错误。

<html>
<body>
<img src="aaa.jpg" />
<script src="/socket.io/socket.io.js">
</script>
<script src="http://code.jquery.com/jquery-1.11.1.js"></script>
<script>
</script>
</body>
</html>

和节点代码

var app = require("express")();
var http = require("http").Server(app);
var io = require("socket.io")(http);
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
    console.log("Server Open");
});

我怎样才能阻止这种情况发生?

要提供静态文件(如图像和脚本),您需要包含一个提供静态文件的中间件。将所有静态文件放在公共目录中,并像这样提供它们。

var express = require("express");
var app = express();
var http = require("http").Server(app);
var io = require("socket.io")(http);
// Serve static files
app.use(express.static(__dirname + '/public'));
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/Movie.html");
});
http.listen(5969, function () {
    console.log("Server Open");
});