viernes, 9 de marzo de 2012

[en] #01 Express framework basic config



This series of posts, are related to the previous post node.js apps with real time which explains how to install the necessary components to develop an application with node.js + socket.IO + MongoDB.
But along the way I thought best to start with some basics, and from them be adding complexity until an application (I have not yet defined, hearing ideas...) which makes use of socket.IO for real-time interactions.

Well, let's start with a very basic introduction to Express frameworks.
This framework is widely used and perfectly combines with socket.IO, is very simple to use and brings many things "out of the box" ready to use.

The first thing we do is create the environment where we will develop this demo, we created the directory for this application and within the structure we create the following subdirectories:
pepo@frank3:~$ mkdir 01-basic_express && cd 01-basic_express
pepo@frank3:~$ mkdir views
pepo@frank3:~$ mkdir node_modules
pepo@frank3:~$ mkdir -p public/img
pepo@frank3:~$ mkdir -p public/css
pepo@frank3:~$ mkdir -p public/js
I will explain each directory use:
views : The directory where our templates lives
node_modules : Where were installed modules it will use
public : Content css, js, imagenes,etc.

once created the directories, open our favorite editor to start developing our app.
The content of this simple example is:
/**
* Module dependencies.
*/

var express = require('express');
var app = module.exports = express.createServer();

// Configuration

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {
layout: false                 
});   
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});

app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});

// Routes

app.get('/',function(req,res){
res.render("index",{
title: "01 - basic express ",                         
banner: "Hello from template!"                        
});                                 
});

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

Now we are going to analyze these lines:
var express = require('express');
var app = module.exports = express.createServer();
In these two lines load the module you need and call the function createServer we return an object with the web server will use to listen to requests and answer them.

Then we go to its configuration, which are the following lines
// Configuration

app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.set('view options', {
layout: false                 
});   
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public'));
});
They first set the directory / views as a repository of templates, for this we use a variable defined globally node.js runtime is __dirname whose value is a string with the absolute path of the directory of your app.
Then we set to "ejs" as our engine for rendering templates, so remember to install the module via npm (npm install ejs).
The final set is to establish that we will not use a layout file for this example, if we wanted we could have a database file for all of our templates or for use only for some pages.
Then we declare the Middlewares we will use the first express.bodyParser () is used for parsing of the post (either json or not) and you return the result parses the variable accessible via req.body , the following is express.methodOverride () that is important to be declared after express.bodyParser () because it performs a check on the variable req.body , this middleware is useful to override the methods of our forms, just an input field with the hidden attribute, like this:
<form action="/" method="post">
<input name="_method" type="hidden" value="put" />
<input name="user[name]" type="text" />
<input type="submit" value="Submit" />
&nbsp;&nbsp;&nbsp; </form>
That will allow us to access the post as follows:
app.put('/', function(){
console.log(req.body.user);    
});
Then we declare the use of app.router which is simply the middleware that contains all the paths defined, and performs route lookup based on the URL of the current request and the HTTP method.
And finally declare the directory from where we provide our static content express.static (__dirname + '/ public') , this allows us to access our resources (in the directory public ) directly referencing it as , note that there is no need to reference the directory public but directly we refer to directories in there

Well, with this we have our first app using node & Express, the code in this first post is on Github Posts


Until next time!

2 comentarios:

  1. Buen post. También hay que mencionar que una forma simple y muy efectiva de empezar con Node y Express es con el ejecutable que nos provee Express (si instalamos globalmente con 'npm install -g express').

    Escribí un post sobre eso: http://vulsai.com/es/code/nodejs-in-321/
    Y un tutorial en codestream: http://codestre.am/6b9ccc5685075ebac3c405a89

    Saludos

    ResponderEliminar
  2. Gracias Dan, voy a chequear tus post. En la próxima semana voy a continuar con los post sobre node. Para la tercer entrega va ser manejo de middlewares y la cuarta interacción con mongoDB.

    Saludos!

    ResponderEliminar