最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Unable to display images using Node.js, Express, and EJS - Stack Overflow

matteradmin7PV0评论

I am working on building my views for a project, and I am running into so trouble getting images to render on my .ejs pages. When the page loads, there is just a little page icon next to the alt text I set in the ejs file. I'm also getting a "GET /public/images/ResConnect.png 404" error in the console. I've tried some solutions online, but nothing seems to work. Here is the code for the specific page I'm trying to get a logo to render on:

<!-- views/index.ejs -->
    <!doctype html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <html>
    <head>
        <title>ResConnect Home</title>
        <link rel="stylesheet" href="//netdna.bootstrapcdn/bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
        <script defer src=".0.8/js/solid.js" integrity="sha384-+Ga2s7YBbhOD6nie0DzrZpJes+b2K1xkpKxTFFcx59QmVPaSA8c7pycsNaFwUK6l" crossorigin="anonymous"></script> <!-- load fontawesome -->
        <script defer src=".0.8/js/fontawesome.js" integrity="sha384-7ox8Q2yzO/uWircfojVuCQOZl+ZZBg2D2J5nkpLqzH1HY0C1dHlTKIbpRz/LG23c" crossorigin="anonymous"></script>
        <style>
            body        { padding-top:80px; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="jumbotron text-center">
                <img src="./public/images/ResConnect.png" alt="ResConnect Logo"/>
                <h1><span class="fa fa-lock"></span> ResConnect Home</h1>
                <p>Please advise: Only approved personnel by The University of Mississippi Department of Student Housing may access ResConnect.</p>

                <b>Login or Register with:</b><br>

                <a href="/login" class="btn btn-default"><span class="fa fa-user"></span> Login</a>
                <a href="/signup" class="btn btn-default"><span class="fa fa-user-plus"></span> Register</a>
            </div>
        </div>
    </body>
    </html>

And here's my server.js file:

// server.js

// get all the tools we need
var express  = require('express');
var session  = require('express-session');
var favicon = require('express-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app      = express();
var port     = process.env.PORT || 1848;

var passport = require('passport');
var flash    = require('connect-flash');


require('./config/passport')(passport); // pass passport for configuration

app.use(favicon(__dirname + './public/images/favicon.ico'));
app.use(express.static('./public/images'));

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({
    secret: 'vidyapathaisalwaysrunning',
    resave: true,
    saveUninitialized: true
 } )); // session secret

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session


require('./app/routes.js')(app, passport); 

app.listen(port);
console.log('Server running on port ' + port);

And here is my get function for the index.ejs page I'm rendering:

app.get('/', function(req, res) {
    res.render('index.ejs'); // load the index.ejs file
});

Additionally, here is my directory setup for the project, so that you can see where all of my files are:

Project file directory

I am working on building my views for a project, and I am running into so trouble getting images to render on my .ejs pages. When the page loads, there is just a little page icon next to the alt text I set in the ejs file. I'm also getting a "GET /public/images/ResConnect.png 404" error in the console. I've tried some solutions online, but nothing seems to work. Here is the code for the specific page I'm trying to get a logo to render on:

<!-- views/index.ejs -->
    <!doctype html>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <html>
    <head>
        <title>ResConnect Home</title>
        <link rel="stylesheet" href="//netdna.bootstrapcdn./bootstrap/3.0.2/css/bootstrap.min.css"> <!-- load bootstrap css -->
        <script defer src="https://use.fontawesome./releases/v5.0.8/js/solid.js" integrity="sha384-+Ga2s7YBbhOD6nie0DzrZpJes+b2K1xkpKxTFFcx59QmVPaSA8c7pycsNaFwUK6l" crossorigin="anonymous"></script> <!-- load fontawesome -->
        <script defer src="https://use.fontawesome./releases/v5.0.8/js/fontawesome.js" integrity="sha384-7ox8Q2yzO/uWircfojVuCQOZl+ZZBg2D2J5nkpLqzH1HY0C1dHlTKIbpRz/LG23c" crossorigin="anonymous"></script>
        <style>
            body        { padding-top:80px; }
        </style>
    </head>
    <body>
        <div class="container">
            <div class="jumbotron text-center">
                <img src="./public/images/ResConnect.png" alt="ResConnect Logo"/>
                <h1><span class="fa fa-lock"></span> ResConnect Home</h1>
                <p>Please advise: Only approved personnel by The University of Mississippi Department of Student Housing may access ResConnect.</p>

                <b>Login or Register with:</b><br>

                <a href="/login" class="btn btn-default"><span class="fa fa-user"></span> Login</a>
                <a href="/signup" class="btn btn-default"><span class="fa fa-user-plus"></span> Register</a>
            </div>
        </div>
    </body>
    </html>

And here's my server.js file:

// server.js

// get all the tools we need
var express  = require('express');
var session  = require('express-session');
var favicon = require('express-favicon');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var morgan = require('morgan');
var app      = express();
var port     = process.env.PORT || 1848;

var passport = require('passport');
var flash    = require('connect-flash');


require('./config/passport')(passport); // pass passport for configuration

app.use(favicon(__dirname + './public/images/favicon.ico'));
app.use(express.static('./public/images'));

// set up our express application
app.use(morgan('dev')); // log every request to the console
app.use(cookieParser()); // read cookies (needed for auth)
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(bodyParser.json());

app.set('view engine', 'ejs'); // set up ejs for templating

// required for passport
app.use(session({
    secret: 'vidyapathaisalwaysrunning',
    resave: true,
    saveUninitialized: true
 } )); // session secret

app.use(passport.initialize());
app.use(passport.session()); // persistent login sessions
app.use(flash()); // use connect-flash for flash messages stored in session


require('./app/routes.js')(app, passport); 

app.listen(port);
console.log('Server running on port ' + port);

And here is my get function for the index.ejs page I'm rendering:

app.get('/', function(req, res) {
    res.render('index.ejs'); // load the index.ejs file
});

Additionally, here is my directory setup for the project, so that you can see where all of my files are:

Project file directory

Share Improve this question asked Mar 25, 2018 at 17:00 Blake LewisBlake Lewis 1133 silver badges11 bronze badges 1
  • Maybe you need /public instead of ./public - in the HTML? EDIT; wasn't reading closely enough. express.static isn't considering public/images to be part of the uri for the files it serves. – Catalyst Commented Mar 25, 2018 at 17:08
Add a ment  | 

1 Answer 1

Reset to default 7

Change

app.use(express.static('./public/images'));

to be

app.use('/public/images/', express.static('./public/images'));

You need express to serve files from the filesystem at ./public/images, but you need to serve those files from the uri under /public/images (instead of just '/')

For example in http://expressjs./en/starter/static-files.html note how the static middleware serves from 'public' but the uris in the sample do not include 'public'.

Adding a path as the argument to any .use mounts the middleware under the given path.

--- EDIT to support favicon.ico not served underneath /public/images

You can alternatively update the directory structure you are using;

app.use(express.static('/path/to/content')); 

where /path/to/content contains

 /
 |-> favicon.ico
 |-> public/
     |-> images/
         |-> x.png
         |-> y.png

So keep in mind express.static serves whatever is inside the path you pass it, at the route it is mounted at (by default '/'). The path it reads from has no bearing on the uris, but the directory structure inside does

Post a comment

comment list (0)

  1. No comments so far