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
.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With