express 2

Regular Expression

app.get('/items/:id([0-9]+)', function(req, res){
	res.send('item no: ' + req.params.id);
});

file

app.get('/hello.txt', function(req, res){
	res.sendfile(__dirname + '/public/hello.txt');
});

public folder読み込み

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

– app.useで読み込む処理をmiddlewareと言う

var logger = require('morgan');
app.use(logger('dev'));
app.use(function(req, res, next){
	console.log('my custom middleware');
	next();
})

$ sudo npm install nodemon -g
$ nodemon app

$ npm install ejs

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

app.get('/', function(req, res){
	res.render('index', {title: 'title'});
});
<body>
	<h1><%= title %></h1>
	hello from index ejs!
</body>
app.param('id', function(req, res, next, id){
	var users = ['yamda', 'nakamura', 'kobayashi'];
	req.params.name = users[id];
	next();
});
app.get('/hello/:id', function(req, res){
	res.send('hello ' + req.params.name);
})

app.get('/bye/:id', function(req, res){
	res.send('hello ' + req.params.name);
})

### Post

var bodyParser = require('body-parser');

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
// ディレクトリ
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// middleware
// app.use(app.router);
var logger = require('morgan');
app.use(logger('dev'));
app.use(express.static(__dirname + '/public'));

app.get('/new', function(req, res){
	res.render('new');
});

app.post('/create', function(req, res){
  //
  	res.send(req.body.name);
})

view, routingの設計をServerサイドの言語ではなく、JavaScriptで書いていける。