Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve the image files using express framework in node.js?

In my application im using express framework to serve the client side files.But while giving background image for the html element.Its showing failed to load given url.

var express = require('express')
    , http  = require('http');

var app = express();
app.configure(function(){
    app.use(express.static(__dirname + '/public'));
});
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(8000);

In public folder i have created javascripts,stylesheets,images folder.Now i'm getting javascripts and stylesheets.But i don't know how to access the image file.

.logo {
    background:url('localhost:8080\logo.jpg');//This image url not loading
    float:left;
    width:20px
    height:20px;
}
like image 263
sachin Avatar asked Mar 13 '13 07:03

sachin


People also ask

How do I use Express to serve images?

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express. The root argument specifies the root directory from which to serve static assets. For more information on the options argument, see express.static.

Can Express serve static files such as images?

js framework, Express facilitates data in a server and includes rendering your static files on the client-side such as images, HTML, CSS, and JavaScript. If you're new to Express, check out our Introduction to Express to get caught up on the basics.

How do I serve a file in node?

var static = require('node-static'); var http = require('http'); var file = new(static. Server)(__dirname); http. createServer(function (req, res) { file. serve(req, res); }).


2 Answers

If your file directory is like

/public
    /stylesheets
    /javascripts
    /images
        /logo.jpg

then your public access begins at the /public directory. This means that in order to access the image, the address would be localhost:8080/images/logo.jpg.

In summary, you had two problems.

  1. Use a forward slash (/), not a backslash (\) in your URLs
  2. You missed including the image directory in the address
like image 50
Nick Mitchinson Avatar answered Oct 21 '22 08:10

Nick Mitchinson


You are also listening on port 8000, but the image you are referencing has port 8080.

like image 31
Shane N Avatar answered Oct 21 '22 07:10

Shane N