我有一个node.js
服务器仅用于提供 .html 文件,设置如下:
var http=require("http");
var express=require("express");
var path=require("path");
var port=process.env.port||5000;
var app=express();
//Serve ALL resource files statically
app.use(express.static(__dirname+"/publicResources"));
app.use(express.static(__dirname+"/private"));
app.get("/",function(req,res)
{
res.sendFile(__dirname+"/publicResources/webpage.html");
});
console.log("We're up");
app.listen(port);
然后在webpage.html中我想使用一个图像,我将其存储在私有(private)目录中:
<img src="../private/puppy.jpg">
当我使用 node
运行此命令时,并在 chrome 中查看它,我收到标准错误消息:
failed to load resource: the server responded with a status of 404 (Not Found)
,关于http://localhost:5000/private/puppy.jpg
。
为什么 .html 文件无法获取图像? - 我知道您需要使用 node.js
提供静态文件,然后使用相对于编写它的 .html 文件的源路径,这两个都是我正在做的(我认为)。这里可能出了什么问题?
最佳答案
express.static()
直接在服务器根目录上提供其文件,没有任何路径前缀。
因此,您实际上正在提供 /puppy.jpg
。
如果您想在 URL 中使用 private/
提供服务,则需要在该路径中挂载 express.static()
:
app.use("private", express.static(__dirname+"/private"));
请参阅documentation .
关于javascript - 在 Node.js 中提供 .html 文件时,如何在单独的目录中获取源文件以在 .html 文件中使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41333590/