0

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

<% 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. If anyone could help out that would be awesome!

1
  • What is the full text of the error message, and what does your directory structure look like? Commented Jun 26, 2017 at 16:58

2 Answers 2

4

Change <img src="public/images/rsz_biopic.jpg"></img> to <img src="images/rsz_biopic.jpg"></img>. Basically, remove public.

You already name public the folder for static files 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 %>
Sign up to request clarification or add additional context in comments.

1 Comment

That fixed it! Thanks so much, I really appreciate your help!
4

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

3 Comments

That's correct. But he needs to require path package.
I'm assuming 'path' is a package I will need to npm install before this example works?
It is built into node I believe.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.