为什么 Node.js 无法识别图像路径

Eth*_*son 0 javascript ejs node.js

我正在尝试使用相对路径节点加载我的图像;但是它一直给我一个 404 错误(未找到)。这是我的代码:

var express = require("express");
var app = express();

app.use(express.static("public"));
app.set("view engine", "ejs");
app.get("/", function(req,res){
  res.render("home");
});


app.get("/fallinlovewith/:thing", function(req, res){
  var thing = req.params.thing; 
  res.render("love", {thingVar: thing});
});


app.get("/posts", function(req, res) {
    var posts = [
        {title: "Post 1", author: "Susy" },
        {title: "My adorable pet Bunny!", author: "Bob" },
        {title: "Can you belive this pomsky?", author: "Ethan" },
      ];

  res.render("posts", {posts: posts});
});

app.listen(process.env.PORT, process.env.IP, function(){
console.log("server started");
});
Run Code Online (Sandbox Code Playgroud)

这是我的 home.ejs 文件

<% include  partials/header %>
<h1>This is the home page</h1>
<img src="https://i.ytimg.com/vi/gp3ZKiwZMvg/hqdefault.jpg">
<img src="public/images/rsz_biopic.jpg"></img>
<% include  partials/footer %>
Run Code Online (Sandbox Code Playgroud)

我的 css 文件和图像 src http 路径都在工作,这只是相对路径。如果有人能帮忙,那就太棒了!

Dam*_*eya 5

更改<img src="public/images/rsz_biopic.jpg"></img><img src="images/rsz_biopic.jpg"></img>。基本上,删除public.

您已经public为静态文件命名了文件夹 app.use(express.static("public"));。不应在文件路径中再次使用它。

<% include  partials/header %>
<h1>This is the home page</h1>
<img src="https://i.ytimg.com/vi/gp3ZKiwZMvg/hqdefault.jpg">
<img src="images/rsz_biopic.jpg"></img>
<% include  partials/footer %>
Run Code Online (Sandbox Code Playgroud)

  • 那就修好了!非常感谢,我真的很感谢你的帮助! (2认同)