1

I am trying to create a SPA app, but when i start my application it does an infinte loop leading to a crash. I am using ExpressJS 4.3.0

App architecture:

public

--partials

----index.jade

server.js

My express code:

var app = express();
var port = process.env.PORT || 8080;

app.set('views', __dirname + '/public');
app.set('view engine', 'jade');

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

app.get('*', function (req, res) {
    res.render('partials/index');
});
app.get('/', function (req, res) {
    res.render('partials/index');
});
app.get('/partials/:name', function (req, res) {
    res.render('/partials/' + req.params.name);
});

app.listen(port);
console.log('Server is running on port: ' + port);

If i use

res.render('/partials/index');

i recieve a message:

Error: Failed to lookup view "/partials/index" in views directory 
Community
  • 1
  • 1

2 Answers2

1

Its because of view lookup function in express view lookup

if (!utils.isAbsolute(path)) path = join(this.root, path);

which makes it assume '/partial/index' is already an absolute path and didnt prefix with root path.

Also move the

app.get('*', function (req, res) {
   res.render('partials/index');
});

to end else it will always serve the index view.

ashu
  • 1,019
  • 7
  • 9
0

It looks like you shouldn't have a preceding / in your view path in render(). Just use 'partials/' + req.params.name.

On a related note, are you sure you want your actual view files to be public? Usually they are stored outside of the public static directory (e.g. ./public contains static assets and ./partials contains views). Also that way you don't have to keep prefixing view paths with partials/.

mscdex
  • 104,356
  • 15
  • 192
  • 153
  • Still doesn't solve the problem with crashing. I'have had 3 different results: Express doesn't find the views/finds the views, but does an infinite loop and crashes/finds the views, but fails to load static files.As for the architecture i will probably move all of those files in a server directory. Thanks for that tip! – user3674178 May 28 '14 at 19:47