express入門

express3.1.1で入門

インストール

$ npm install -g express
$ npm link express

でローカルディレクトリにリンクを張れる。

$ ll node_modules
total 8
lrwxr-xr-x  1 maki  staff    45B  4  7 21:35 express -> /usr/local/share/npm/lib/node_modules/express

Hello Word

hello.js

var express = require('express')
var app = express();
app.get('/', function(request, response) {
    response.send('Hello World!');
});
app.listen(8080);

実行

$ node hello.js

expressコマンドでアプリケーション雛形作成

$ express test

   create : test
   create : test/package.json
   create : test/app.js
   create : test/public
   create : test/public/javascripts
   create : test/public/images
   create : test/public/stylesheets
   create : test/public/stylesheets/style.css
   create : test/routes
   create : test/routes/index.js
   create : test/routes/user.js
   create : test/views
   create : test/views/layout.jade
   create : test/views/index.jade

   install dependencies:
     $ cd test && npm install

   run the app:
     $ node app

表示されているとおり、

$ cd test
$ npm install
$ node app

で3000番ポートでHTTPサーバーが立ち上がる

JSONをさばく

var express = require('express')
  , http = require('http')
  , path = require('path');

var app = express();
app.set('port', process.env.PORT || 3000);
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(path.join(__dirname, 'public')));

// development only                                                                                                                             
if ('development' == app.get('env')) {
  app.use(express.errorHandler());
}

app.post('/status', function (req, res) {
    var text = req.body.text || 'OK';
    res.send({text: text});
});

http.createServer(app).listen(app.get('port'), function(){
    console.log('Express server listening on port ' + app.get('port'));
});

curlでたたく

$ curl -X POST -H 'Content-Type: application/json' -d '{"text":"Hello"}' -v http://localhost:3000/status
* About to connect() to localhost port 3000 (#0)
*   Trying ::1...
* Connection refused
*   Trying 127.0.0.1...
* connected
* Connected to localhost (127.0.0.1) port 3000 (#0)
> POST /status HTTP/1.1
> User-Agent: curl/7.24.0 (x86_64-apple-darwin12.0) libcurl/7.24.0 OpenSSL/0.9.8r zlib/1.2.5
> Host: localhost:3000
> Accept: */*
> Content-Type: application/json
> Content-Length: 16
> 
* upload completely sent off: 16 out of 16 bytes
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Content-Type: application/json
< Content-Length: 16
< Date: Tue, 09 Apr 2013 02:48:23 GMT
< Connection: keep-alive
< 
* Connection #0 to host localhost left intact
{"text":"Hello"}* Closing connection #0