[英]How do I source files in a separate directory for use in the .html file when serving the .html file in node.js?
我有一个仅用于提供.html文件的node.js
服务器,设置如下:
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中,我想使用一个图像,该图像存储在私有目录中:
<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"));
请参阅文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.