admin管理员组

文章数量:1313314

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

本文标签: javascriptUnable to display images using NodejsExpressand EJSStack Overflow