11

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.

4 Answers 4

30

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 
Sign up to request clarification or add additional context in comments.

Comments

6

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.

Comments

3

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 

Comments

0
app.use('/static', express.static('./public')); app.listen(2020, () => { console.log("Server Started"); }) 

Run: localhost:2020/static/test.jpg

1 Comment

Welcome to Stack Overflow! While this code may solve the question, including an explanation of how and why this solves the problem would really help to improve the quality of your post, and probably result in more up-votes. Remember that you are answering the question for readers in the future, not just the person asking now. Please edit your answer to add explanations and give an indication of what limitations and assumptions apply.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.