简体   繁体   English

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

[英]Why Node.js not recognizing image path

I'm trying to get my images to load up using node the relative path; 我正在尝试使用节点的相对路径加载我的图像; however it keeps giving me a 404 error (not found). 但是它一直给我一个404错误(未找到)。 Here is my code: 这是我的代码:

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

Here is my home.ejs file 这是我的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 %>

My css file, and image src http path are both working, It's just the relative path. 我的css文件和image src http路径都可以正常工作,这只是相对路径。 If anyone could help out that would be awesome! 如果有人可以帮忙,那就太好了!

Change <img src="public/images/rsz_biopic.jpg"></img> to <img src="images/rsz_biopic.jpg"></img> . <img src="public/images/rsz_biopic.jpg"></img>更改为<img src="images/rsz_biopic.jpg"></img> Basically, remove public . 基本上,删除public

You already name public the folder for static files app.use(express.static("public")); 您已经将public静态文件的文件夹命名为app.use(express.static("public")); . It shouldn't be used again in the path for the files. 不应在文件路径中再次使用它。

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

Add to top of file: 添加到文件顶部:

var path = require('path'),

You need to define that path in node. 您需要在节点中定义该路径。

Change: 更改:

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

To: 至:

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

This way "/public" is a valid location 这样“ / public”是有效位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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