Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve images in nodejs express

I have this code

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

var app = express();
var server = http.createServer(app);

app.use(express.static(__dirname + '/uploads'));

console.log("listen to 8080");
server.listen(8080);

I have my image in /uploads/test.jpg but when I go to http://localhost:8080/uploads/test.jpg I get Cannot GET /uploads/test.jpg.

like image 723
user3631341 Avatar asked Apr 28 '15 13:04

user3631341


3 Answers

The static method indicates which root folder you will be serving your static content from. At the moment, your image will be accessible from http://localhost:8080/test.jpg.

To serve the images from a sub-folder, you would need to create this folder inside the static directory e.g.

app.use(express.static(__dirname + '/public'));

- public
-- uploads
---- test.jpg
like image 164
James Avatar answered Nov 14 '22 03:11

James


app.use function has a default of '/' . When a route other than '/' is given , the middle-ware handle is useful only when the path segment is in the requests path name. For example if we mount a function in '/example' it would be invoked on /example and not at '/'. So your request is at "/uploads/test.jpg" To do this

app.use('/uploads', express.static(__dirname + '/public'));

Now the middle ware is mounted at '/uploads' and services and any request made with path '/uploads' like GET /uploads/test.jpg etc.

like image 25
Imprfectluck Avatar answered Nov 14 '22 02:11

Imprfectluck


Use the following code to serve images, CSS files, and JavaScript files in a directory named public.

var express = require('express');
var app = express();
app.use(express.static('public'));

Now, you can load the files that are in the public directory:

Examples:

localhost:3000/images/kitten.jpg
localhost:3000/css/style.css
localhost:3000/js/app.js
like image 2
jaiaswani Avatar answered Nov 14 '22 01:11

jaiaswani