Sky Sky - 1 year ago 73
Node.js Question

displaying a simple image in expressjs


  • I have a image called
    image.jpg
    stored in location
    /public/images/images.jpg
    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);


app.get('/',function(request,response){
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'});
response.end(JSON.stringify(rows));
});

} );



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

http://54.218.73.244:7005/image.jpg


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:

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

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.