danielgormly
danielgormly

Reputation: 1070

Can't get second level routes working in express

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

server.js

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.

Upvotes: 0

Views: 624

Answers (2)

Subham
Subham

Reputation: 1465

try this:

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

Upvotes: 1

user2879704
user2879704

Reputation:

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
staff.post('/test', function(req, res, next){
  res.json(some-json-content)
})

Upvotes: 1

Related Questions