user3631341
user3631341

Reputation: 525

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.

Upvotes: 11

Views: 29736

Answers (4)

Harshvardhan Patil
Harshvardhan Patil

Reputation: 1

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

app.listen(2020, () => {
  console.log("Server Started");
})

Run: localhost:2020/static/test.jpg

Upvotes: 0

jaiaswani
jaiaswani

Reputation: 31

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

Upvotes: 3

James
James

Reputation: 82096

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

Upvotes: 29

Imprfectluck
Imprfectluck

Reputation: 684

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.

Upvotes: 6

Related Questions