xdfil
xdfil

Reputation: 291

New to express, where do I start?

I’m learning node/express. I’ve purchased a few books and have followed some online guides and I would like to start tinkering around but I can’t figure out where to add logic to my routes. I created a basic app using the express command line tool. I now have two routes defined in my app.js

app.get('/', routes.index);
app.get('/users', user.list);

I see the jade templates and I think I am fully capable of serving plain old html through jade/stylus. But I want to add logic and I don’t see where to do that. Does it work like php, as in do I add the logic to the jade html files, or do I put it in the app.js somehow.

I saw in one example how to reference a variable in jade, but I would like to run code (server side, like php) when the page is displayed.

I’m referencing php a lot because it’s the only language I am familiar with.

Upvotes: 2

Views: 79

Answers (1)

Plato
Plato

Reputation: 11052

a common pattern is to separate logic into functions that you call from your routes, you can put these in separate files

var express = require('express');
var app = express();
require('http').createServer(app).listen(3000);
app.use(express.logger());
app.use(express.bodyParser());
app.use(app.router);
app.set('views', __dirname + '/templates');
app.set('view engine', 'jade');

var myLib = require('lib/myLib.js');
// myLib will contain: module.exports = { foo:function(req, arg, callback){ ... } };

app.get('/', function(req, res){
  myLib.foo(req, 'hello', function(err, result){
    // this is passed into foo as `callback` and generally is called from foo
    if(err){ return res.send(500) };
    res.send(200, 'Foo was ' + result);
  });
});

// edit - ways to structure this with app.render for a jade template
app.get('/jade1', function(req, res){
  myLib.bar(req, res); 
  // it is now myLib.bar's responsibility to send a response with the `res` object,
  // either with res.end, res.send, res.render, res.redirect or whatever
});

// my preferred way: (i usually try to keep my logic separated from req/res)
app.get('jade2', function(req, res){
  var username = req.body.username;
  myLib.getUser(username, function(err, result){
    if(err){ return res.send(500) };
    res.locals.foobar = 'hello world';     
    // res.locals.x is equivalent to passing {x:_} inline to render as below: 
    res.render('jade2', {user: result});
  });
});

Upvotes: 2

Related Questions