Download Linux Journal | May 2011 | Issue 205

Transcript
your application.
Then, you tell the application that when it
receives a GET request for the '/' path, it should
execute the function that you indicate. Notice that
you don’t have to deal with the low-level details of
HTTP responses here. You simply can send your
response and be done with it.
You then tell the application to listen on port 3000.
You can save and run your application, and when you
go to /, you get your greeting.
Well, what else can you do? I’ve expanded
express.js a bit and put it into Listing 1. To begin
with, you can see that by specifying a Rails-style
route (/person/:id) with a colon in front of one of
the path segments, you can set a parameter name
that is retrieved automatically, and that is then
available via app.params.id:
app.get('/person/:id', function(req, res){
res.send('Oh, you want information about person '
¯+ req.params.id + "\n");
});
Going to /person/100 will result in the output:
Oh, you want information about person 100
which means that the parameter can be used as the
key in a database, for example. (And if you wonder
whether Node.JS can talk to a database, be aware
that there are adapters for many of them—both
relational databases, such as MySQL and PostgreSQL,
and also non-relational databases, such as MongoDB,
Redis and CouchDB.)
You aren’t limited to GET requests:
app.post('/foo', function(req, res){
res.send("You requested foo\n");
});
If you ask for /foo via a POST request, you will get
this response. But if you ask for /foo via GET, you will
receive a 404 error from Node.JS.
Finally, you also can use templates on the filesystem.
One particularly Ruby-style template is called ejs,
and it has a virtually identical syntax to Ruby’s ERb
(embedded Ruby), including the need for a “views”
directory and for a layout. Create a views subdirectory,
and put index.ejs in it, as per Listing 2. You then