I'm trying to get my express to serve up static files that are in another location:
This is the current directory I have:
|__client
| |__thumbnails.html
|
|__server
|__app.js
I tried to just use app.use(express.static(path.join(__dirname, '..', 'client')));, but it wouldn't serve the file at all. However, when I used the same path.join for a get request on '/' it will send the file.
Here it the code I have at the moment. It's working, thank God, but I want to see if there is a way for me to serve it without actually sending the file.
const express = require('express');
const path = require('path');
const similar = require('./routes/similar');
const image = require('./routes/images');
const app = express();
app.use(express.static(path.join(__dirname, '..', 'client')));
app.use('/item', similar);
app.use('/thumbnail', image);
app.get('/', (req, res) => res.status(200).sendFile(path.join(__dirname, '..', 'client', 'thumbnail.html')));
module.exports = app;
You can make the file anything you want, through configuration of the serve-static module:
https://expressjs.com/en/resources/middleware/serve-static.html
From that page:
var express = require('express')
var serveStatic = require('serve-static')
var app = express()
app.use(serveStatic('public/ftp', {'index': ['default.html', 'default.htm']}))
app.listen(3000)
now anything that you put in the 'index' array will be looked at, in the order you defined.
Otherwise, you would still be able to get to your html file if you put the actual filename in the url.
Okay I think I figured it out. So apparently you have to have the html saved as index. Express is looking for that, but since I don't have an index.html it skips my thumbnails.html.
So renaming my html to index.html fixed the issue.
UPDATE:
So reading through the documentation, you can set the what the default is by passing in an options. I passed in { index: 'thumbnails.html' } as the second argument for static and it serves my html.
Related
I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })
I want to serve index.html and /media subdirectory as static files. The index file should be served both at /index.html and / URLs.
I have
web_server.use("/media", express.static(__dirname + '/media'));
web_server.use("/", express.static(__dirname));
but the second line apparently serves the entire __dirname, including all files in it (not just index.html and media), which I don't want.
I also tried
web_server.use("/", express.static(__dirname + '/index.html'));
but accessing the base URL / then leads to a request to web_server/index.html/index.html (double index.html component), which of course fails.
Any ideas?
By the way, I could find absolutely no documentation in Express on this topic (static() + its params)... frustrating. A doc link is also welcome.
If you have this setup
/app
/public/index.html
/media
Then this should get what you wanted
var express = require('express');
//var server = express.createServer();
// express.createServer() is deprecated.
var server = express(); // better instead
server.configure(function(){
server.use('/media', express.static(__dirname + '/media'));
server.use(express.static(__dirname + '/public'));
});
server.listen(3000);
The trick is leaving this line as last fallback
server.use(express.static(__dirname + '/public'));
As for documentation, since Express uses connect middleware, I found it easier to just look at the connect source code directly.
For example this line shows that index.html is supported
https://github.com/senchalabs/connect/blob/2.3.3/lib/middleware/static.js#L140
In the newest version of express the "createServer" is deprecated. This example works for me:
var express = require('express');
var app = express();
var path = require('path');
//app.use(express.static(__dirname)); // Current directory is root
app.use(express.static(path.join(__dirname, 'public'))); // "public" off of current is root
app.listen(80);
console.log('Listening on port 80');
express.static() expects the first parameter to be a path of a directory, not a filename. I would suggest creating another subdirectory to contain your index.html and use that.
Serving static files in Express documentation, or more detailed serve-static documentation, including the default behavior of serving index.html:
By default this module will send “index.html” files in response to a request on a directory. To disable this set false or to supply a new index pass a string or an array in preferred order.
res.sendFile & express.static both will work for this
var express = require('express');
var app = express();
var path = require('path');
var public = path.join(__dirname, 'public');
// viewed at http://localhost:8080
app.get('/', function(req, res) {
res.sendFile(path.join(public, 'index.html'));
});
app.use('/', express.static(public));
app.listen(8080);
Where public is the folder in which the client side code is
As suggested by #ATOzTOA and clarified by #Vozzie, path.join takes the paths to join as arguments, the + passes a single argument to path.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
If you have a complicated folder structure, such as
- application
- assets
- images
- profile.jpg
- web
- server
- index.js
If you want to serve assets/images from index.js
app.use('/images', express.static(path.join(__dirname, '..', 'assets', 'images')))
To view from your browser
http://localhost:4000/images/profile.jpg
If you need more clarification comment, I'll elaborate.
use below inside your app.js
app.use(express.static('folderName'));
(folderName is folder which has files) - remember these assets are accessed direct through server path (i.e. http://localhost:3000/abc.png (where as abc.png is inside folderName folder)
npm install serve-index
var express = require('express')
var serveIndex = require('serve-index')
var path = require('path')
var serveStatic = require('serve-static')
var app = express()
var port = process.env.PORT || 3000;
/**for files */
app.use(serveStatic(path.join(__dirname, 'public')));
/**for directory */
app.use('/', express.static('public'), serveIndex('public', {'icons': true}))
// Listen
app.listen(port, function () {
console.log('listening on port:',+ port );
})
I would add something that is on the express docs, and it's sometimes misread in tutorials or others.
app.use(mountpoint, middleware)
mountpoint is a virtual path, it is not in the filesystem (even if it actually exists). The mountpoint for the middleware is the app.js folder.
Now
app.use('/static', express.static('public')`
will send files with path /static/hell/meow/a.js to /public/hell/meow/a.js
This is the error in my case when I provide links to HTML files.
before:
<link rel="stylesheet" href="/public/style.css">
After:
<link rel="stylesheet" href="/style.css">
I just removed the static directory path from the link and the error is gone. This solves my error one thing more don't forget to put this line where you are creating the server.
var path = require('path');
app.use(serveStatic(path.join(__dirname, 'public')));
You can achieve this by just passing the second parameter express.static() method to specify index files in the folder
const express = require('express');
const app = new express();
app.use(express.static('/media'), { index: 'whatever.html' })
I have a folder called "Public" which contains an index.html file a long with some JavaScript and library files. When someone tries to access the products path (mydomain.com/products) I want to display that index.html file, but the client also needs to receive all the JavaScript and libraries. Here is the code for how I initially handle the HTTP request.
const express = require('express')
const app = express()
const bodyParse = require('body-parser')
const productRoutes = require('./api/routes/products')
const orderRoutes = require('./api/routes/orders')
app.use(bodyParse.urlencoded({extended: false}))
app.use(bodyParse.json())
// Routes which handle requests
app.use('/products', productRoutes)
app.use('/orders', orderRoutes)
In the products.js file, I continue the routing like this:
const express = require('express')
const router = express.Router()
router.get('/', (req, res, next) => {
/*res.status(200).json({
message: 'Handling GET requests to /products'
})*/
res.status(200).render("../../public")
})
The code I've commented out works perfectly fine, but I'm struggling to respond with the "public" folder page. I can't remember everything I've tried, but using .render or .sendFile on the "public" directory has not worked for me.
When I try to access the /products route, I'm hit with an empty error message. As it fails to return anything in the /products route, in continues down the file to an error handler. The error message is empty.
Any ideas on how to display the page with all the folder contents would be great!
Try: app.use('/products', express.static('public'))
This makes your "public" directory viewable from the /products route.
express.static() docs
You must config path for express static by :
//app.js | server.js
app.use(express.static(__dirname + '/public'));
Then, in example you have a file as : /public/you.html
In your app, you can use that file as path /you.html
And the same with all files type *.js, *.css,...
Fix error cannot view error
Run cmd npm install ejs
Att to app.js:
app.set('view engine', 'ejs');
After that, you create 1 file error.ejs at folder views :
//error.ejs
<%=error%>
Goodluck
I want to change the static path based on the route. For example (not working):
const app = express();
const appRouter = express.Router();
const adminRouter = express.Router();
appRouter.use(express.static('/path/to/app/static/assets');
adminRouter.use(express.static('/path/to/admin/static/assets');
app.use('/', appRouter);
app.use('/admin', adminRouter);
This also does not work:
const app = express();
app.use('/', express.static('/path/to/app/static/assets');
app.use('/admin', express.static('/path/to/admin/static/assets');
What I do not want to do is set both paths as static for the entire app:
// the following will expose both paths as static for the entire app
// this does not accomplish what I am trying to do
const app = express();
app.use(express.static('/path/to/app/static/assets');
app.use(express.static('/path/to/admin/static/assets');
Is this possible?
What you are trying to accomplish is not possible from your approach with express.static(). Your #2 approach does create virtual path prefix (where the path does not actually exist in the file system) for files that are served by the express.static function. Follow this for more info.
But what seems can be done is changing the path of express.static() in run time. Please follow through this git issue. Hope it helps.
I don't think it is possible with Express static middleware.
I was able to come up with a solution following the git issue posted by Tolsee. I published it to npm under the name express-dynamic-static.
Here is quick example of how to use it:
const express = require('express');
const dynamicStatic = require('express-dynamic-static')(); // immediate initialization
const path = require('path');
const app = express();
app.use(dynamicStatic);
app.get('/', (req, res) => {
dynamicStatic.setPath(path.resolve(__dirname, 'path/to/app/assets'));
// res.render...
}
app.get('/admin', (req, res) => {
dynamicStatic.setPath(path.resolve(__dirname, 'path/to/admin/assets'));
// res.render...
}
I have a Node.js server which implements a set of base files that I want to serve as a default. Then other users of the server can require() it and overload some defaults and perhaps add additional files. For example:
server_base
/site
-> index.html 'A'
-> images 'A'
-> icon.jpg
user_server (requiring server_base)
/site
-> index.html 'B'
-> images 'B'
-> picture.jpg
The resulting website would have the merged set of those files with the user's index.html taking precedence over the base.
So far I've been trying to accomplish this with express since the use() method should allow for this hierarchy to be established.
server_base.js
var express = require('express'),
app = module.exports = express(),
server = null;
app.configure( function() {
server = require('http').createServer(app);
app.use('/', express.static(__dirname + '/site'));
server.listen(80);
});
user_site.js
var express = require('express'),
app = express(),
sb = require('../server_base');
app.configure( function() {
app.use('/', express.static(__dirname + '/site'));
app.use(sb); // server_base configure occurs here
});
As I understand it, if express finds a requested file in the first referenced root path (user_site's in this case) it should return that file. If not and its found in the other path, it should return that file (server_base). What I'm seeing though is that the '/' path is being totally wiped out with whatever the second call to use('/', ...) provided.
I figured perhaps it was the configure() call occurring twice and effectively wiping out settings. So I then tried exporting from server_base it's site path so that the user_site would app.use(...) it's own path followed by the server_base's. This results in a site somehow unable to serve any files.
I'm pretty new to Node.js and Express so if there is a better/cleaner way to make an easily-distributable and extendable server_base, I'm open to alternatives.
The order of the middlewares is important. You need to make your server base add it's static handler after the user has had time to add its static handler, something like this:
user_site.js:
var express = require('express'),
app = express(),
sb = require('./server_base');
app.use('/', express.static(__dirname + '/site'));
sb(app); // server_base configure occurs here
app.listen(8080);
server_base.js:
var express = require('express');
module.exports = function(app) {
app.use('/', express.static(__dirname + '/site'));
return app;
};