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

时间:2017-06-26 16:52:23

标签: javascript node.js ejs

我试图让我的图像使用节点加载相对路径;但它一直给我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");
});

这是我的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 %>

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

2 个答案:

答案 0 :(得分:3)

<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 %>

答案 1 :(得分:3)

添加到文件顶部:

var path = require('path'),

您需要在节点中定义该路径。

更改:

app.use(express.static("public"));

致:

app.use("/public", express.static(path.join(__dirname, 'public')));

这样“/ public”是一个有效的位置

相关问题