簡體   English   中英

在node.js中投放.html文件時,如何在單獨的目錄中獲取文件以在.html文件中使用?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM