我是Node.js的新手,无法找到解决问题的方法。我已经使用Node.js编写了一个服务器来提供html网页。问题是它不会显示同一文件夹中的图像。我正在尝试提供我的网页以及我的图像和CSS文件。任何帮助将不胜感激。
相关代码:
服务器:
var http = require('http');
var fs = require('fs');
const PORT = 8080;
function handleRequest(request, response) {
console.log(request.url);
var bool = 0;
var index = fs.readFileSync("index.html", {
encoding: "utf-8"
});
if(request.url == "/")
{
bool = 1;
response.end(index);
}
else if(request.url == "/index" || request.url == "/index.html")
{
bool = 1;
response.end(index);
}
else if(bool == 0)
{
response.statusCode = 404;
response.end("Not Found");
}
}
var server = http.createServer(handleRequest);
server.listen(PORT, function() {
console.log("Started server on http://localhost:%s", PORT)
});
HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>My Personal Webpage</title>
<link rel="stylesheet" href="index-css.css"/>
</head>
<body>
<h1>Welcome!</h1>
<p>My paragraph.</p>
<img src="/family.jpg" alt="Family" style="width:342px;height:513px;">
<img src="/Another.jpeg" alt="Another" style="width:500px;height:500px;">
</body>
</html>
答案 0 :(得分:0)
我建议使用CALayer
来公开文件夹以向客户端提供静态文件。 Here is the documents关于使用express提供静态文件。
编辑:以下是使用快递
提供index.html的简单工作示例app.use(express.static(__dirname + '/FOLDER_NAME'))