Sky Sky - 1 year ago 95
Node.js Question

displaying a simple image in expressjs

  • I have a image called
    stored in location
    in the express folder

My express program is below ::

var express = require('express')
, http = require('http')
, mysql = require('mysql'); // <---- HERE

var app = express();

var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: "root",
database: 'test123'

connection.connect(); // <---- AND HERE

// all environments
app.set('port', process.env.PORT || 7005);

connection.query('SELECT * FROM MyTable', function(err, rows, fields)

console.log('Connection result error '+err);
console.log('no of records is '+rows.length);
response.writeHead(200, { 'Content-Type': 'application/json'});

} );

http.createServer(app).listen(app.get('port'), function(){
console.log('Express server listening on port ' + app.get('port'));

I am not able to display the image from the locaton where i have stored when i give

Where am i going wrong with my code

Answer Source

Express does not handle serving assets or static files. However, the static() middleware was written for this purpose. Just add this line of code:


This middleware will start a static file server mounted to /, and will serve files from the /public/images directory. Accessing http://url.ext/image.jpg will serve the image file from /public/images/image.jpg.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download