3. Proxy
module.exports.initRoutes = () => Promise.resolve().then(() => {
app.use('/', require('routes/index'));
app.use('/api', require('routes/api'));
app.use('/auth', require('routes/auth'));
if (config.get('NODE_ENV') === 'development') {
app.use('/test', require('routes/test'));
}
// restricted access
app.use('/users', require('routes/users'));
// SPA fallback to index.html
app.use((req, res, next) => {
if ((req.method === 'GET' || req.method === 'HEAD') && req.accepts('html')) {
res.sendFile('index.html', { root: path.join(__dirname, config.get('http_server:staticDir')) }, err => err && next());
} else next();
});
// catch 404 and forward to error handler
app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use((err, req, res, next) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
});