简体   繁体   中英

Node.js + Express.js : express.static not serving image (contains errors)

I'm trying to use express.static to serve an image at http://localhost:3000/logo/logo.jpg . The image logo.jpg is in /public/images and my code is:

    app.use("/logo", express.static(__dirname + '/public/images'));

The page loads, but the image is broken. Firefox says: The image at http://localhost:3000/logo/logo.jpg cannot be displayed because it contains errors. When I look at the page info, Firefox tells me the image dimensions for logo.jpg are 0x0. I've tried using various images and different browsers, but they all have the same issue.

How can I get the image to load properly?

I couldn't get my directory with static files served, but when I started to use path.join it began to work as expected. Try this:

var path = require('path');
app.use('/logo', express["static"](path.join(__dirname, 'public/images')));

I found the culprit. For some reason, if I placed the line:

app.use("/logo", express.static(__dirname + '/public/images'));

after this code:

// load liveReload script only in development mode
// load before app.router
// development only
if ('development' == app.get('env')) {
  var liveReloadPort = 35729;
  var excludeList = ['.woff', '.flv'];

  app.use(require('connect-livereload')({
      port: liveReloadPort,
      excludeList: excludeList
    }))
}

It didn't work. However, if I moved the app.use("/logo")... line before the liveReload code, it works.

Don't exactly understand why the position affected how the code works, but at least it does!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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