简体   繁体   中英

How do I source files in a separate directory for use in the .html file when serving the .html file in node.js?

I have a node.js server just for serving a .html file , set up like this:

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);

And then in webpage.html I want to use an image, which I'm storing in the private directory:
<img src="../private/puppy.jpg">

When I run this with node , and view it in chrome, I get the standard error message: failed to load resource: the server responded with a status of 404 (Not Found) , pertaining to http://localhost:5000/private/puppy.jpg .

Why can't the .html file source the image? - I understand that you need to serve the static files with node.js , and then use the source path relative to the .html file in which it is written, both of which I am doing (I think). What might be going wrong here?

express.static() serves its files directly on the server root, without any path prefix.

Therefore, you're actually serving /puppy.jpg .

If you want to serve it with private/ in the URL, you need to mount express.static() in that path:

app.use("private", express.static(__dirname+"/private"));

See the documentation .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM