Can't get second level routes working in express

danielgormly Source

I'm sorry I'm reasonably new to node. I've been stuck on this for a couple hours.


app.use(express.static(__dirname + "/public"));

app.get('/', function(req, res){
  res.sendFile(path.resolve(templatesPath + 'index.html'));

app.get('*', function(req, res){
  res.sendFile(path.resolve(templatesPath + 'index.html'));

index.html is an Angular application. I have the first level of routes working fine using Angular's HTML5 routes eg. "http://lh:3000/staff" or "http://lh:3000"

but if I add another level or route parameters, e.g. "http://lh:3000/staff/" or "http://lh:3000/staff/test" Express seems to ignore express.static and instead uses the get wildcard to turn all my files into index.html so my page breaks.

Thanks for your help answerers

In secondary routes, it was loading assets referenced in index.html, relative to the secondary route. My temp solution is to add: app.use('/files/',express.static(path.join(__dirname + "/public"))); but I realise now it is better to change my solution.



answered 3 years ago Madhavan Kumar #1

are staff/test, static assets sitting inside your assets folder? If they are static assets, there must be a file in the path staff/test inside your assets folder.

if they are not static assets and they are dynamic content, consider using express.router,make a router for staff and add it as,

var staff = express.Router();
staff.use('/staff', staff)

//this is route handler for /staff/test'/test', function(req, res, next){

answered 3 years ago Subham #2

try this:

app.get('*/*', function(req, res){
  res.sendFile(path.resolve(templatesPath + 'index.html'));

comments powered by Disqus