I wrote this as a way to deliver static portion of the app. I'm wondering if there is a better way to write this, as I am new to Express.
The goal is to let a single-page app to handle routing as needed. There is an API layer of this app that is defined under the /api/ route namespace.
I wanted to note that all assets are served from /app folder and are not public. I can adjust that, but as of now, that's the folder structure. /app is a compilation destination. root folder contains server.js where the below code resides and contains app/ and src/ folders, as well as server/ folder that contains API related stuff.
var express = require('express');
var http = require('http');
var path = require('path');
var app = express();
require('./express/api')(app);
app.get("/css/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get("/js/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get("/img/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get("/pages/*",function(req,res){
res.sendfile('app'+req.path);
});
app.get('*',function(req,res){
res.sendfile('app/index.html');
});
app.listen(3000);
console.log('Listening on port 3000');
1 Answer 1
There is a better way.
If you wish to serve static files with express - it comes bundled with static
middleware. To use it, you simply add this line before your routes:
app.use(express.static(__dirname + '/public'));
This may require slight adjustment to your paths but it replaces all those manual routes and is more efficient (caching, expiration etc).
I would, however, suggest that you use something like nginx
for your static assets since it's typically more robust and it'll free resources from your node server.
-
\$\begingroup\$ thanks @diversario, this would require me to adjust my build process, is there a way to set the public directory to something else. I will look at it my self, just maybe you know. \$\endgroup\$GnrlBzik– GnrlBzik2013年08月19日 15:59:18 +00:00Commented Aug 19, 2013 at 15:59
-
1\$\begingroup\$ You can set the directory to anything you like, just make sure it contains only public assets. \$\endgroup\$diversario– diversario2013年08月19日 19:15:08 +00:00Commented Aug 19, 2013 at 19:15
-
\$\begingroup\$ This works great, so i just had to add this before any routes, and then just leave wild card to serve index.html \$\endgroup\$GnrlBzik– GnrlBzik2013年08月20日 19:58:00 +00:00Commented Aug 20, 2013 at 19:58
-
1\$\begingroup\$ If the index.html is within your public directory it will be serve as well. You don't need a specific route for it. \$\endgroup\$jackdbernier– jackdbernier2014年03月17日 14:18:10 +00:00Commented Mar 17, 2014 at 14:18
-
\$\begingroup\$ Note that the middleware must come before the wildcard definition in order to work. \$\endgroup\$Amin NAIRI– Amin NAIRI2019年03月08日 19:51:29 +00:00Commented Mar 8, 2019 at 19:51