express blog system

expressで簡易ブログをつくります。

var bodyParser = require('body-parser');
var logger = require('morgan');
var express = require('express'),
 app = express()
 post = require('./routes/post');

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.methodOverride());

app.use(logger('dev'));
app.use(function(err, req, ers, next){
  res.send(err.message);
});

// csrf対策
app.use(express.cookieParser());
app.use(express.session({secret: '386424ggrsr'}));
app.use(express.csrf());
app.use(function(req, res, next){
  res.locals.csrftoken = req.csrfToken();
  next();
});

// routing
app.get('/', post.index);
app.get('/posts/:id([0-9]+)', post.show);
app.get('/posts/new', post.new);
app.post('/posts/create', post.create);
app.get('/posts/:id/edit', post.edit);
app.put('/posts/:id', post.update);
app.delete('/posts/:id', post.destroy);
/*


app.get('/new', function(req, res){
  res.render('new');
});
*/
 app.listen(3000);
 console.log("server starting...");

post.js

var bodyParser = require('body-parser');
var logger = require('morgan');
var express = require('express'),
 app = express()
 post = require('./routes/post');

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');

// middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(express.methodOverride());

app.use(logger('dev'));
app.use(function(err, req, ers, next){
  res.send(err.message);
});

// csrf対策
app.use(express.cookieParser());
app.use(express.session({secret: '386424ggrsr'}));
app.use(express.csrf());
app.use(function(req, res, next){
  res.locals.csrftoken = req.csrfToken();
  next();
});

// routing
app.get('/', post.index);
app.get('/posts/:id([0-9]+)', post.show);
app.get('/posts/new', post.new);
app.post('/posts/create', post.create);
app.get('/posts/:id/edit', post.edit);
app.put('/posts/:id', post.update);
app.delete('/posts/:id', post.destroy);
/*


app.get('/new', function(req, res){
  res.render('new');
});
*/
 app.listen(3000);
 console.log("server starting...");

index.html

<% include ../header %>
<body>
 <h1>Posts</h1>
 <ul>
   <% for (var i = 0; i < posts.length; i++){%>

   <li><a href="/posts/<%= i %>"><%= posts&#91;i&#93;.title %></a></li>
   <li><a href="/posts/<%= i %>/edit">[Edit]</a></li>
   <form method="post" action="/posts/<%= i %>">
     <input type="submit" value="del">
     <input type="hidden" name="_csrf" value="<%= csrftoken %>">
       <input type="hidden" name="_method" value="delete">
       <input type="hidden" name="id" value="<%= i %>">
   </form>
 </li>
   <% } %>
 </ul>
 <p><a href="/posts/">Add new</a></p>
<% include ../footer %>

post

var posts = [
  {title: 'title0', body: 'body0'},
  {title: 'title1', body: 'body1'},
  {title: 'title2', body: 'body2'},
];

exports.index = function(req, res){
  res.render('posts/index', {posts: posts});
};
exports.show = function(req, res){
  res.render('posts/show', {post: posts[req.params.id]});
};
exports.update = function(req, res, next){
  if (req.body.id !== req.params.id){
    next(new Error('ID not valid'));
  }else {
  posts[req.body.id] = {
    title: req.body.title,
    body: req.body.body
  };
  res.redirect('/');
};
exports.destroy = function(req, res, next){
  if (req.body.id !== req.params.id){
    next(new Error('ID not valid'));
  }else {
  posts.splice(req.body.id, 1);
  res.redirect('/');
}
};
exports.show = function(req, res){
  res.render('posts/new');
};
exports.create = function(req, res){
  var post = {
    title: req.body.title,
    body: req.body.body
  };
  posts.push(post);
  res.redirect('/');
};
exports.edit = function(req, res){
  res.render('posts/edit', {post: posts[req.params.id], id: req.params.id});
};

edit

<% include ../header %>
<body>
 <h1>Edit</h1>
<form method="post" action="/posts/<%= id %>">
  <input type="text" name="title" value="<%= post.title %>">
  <input type="text" name="body" value="<%= post.body %>">
  <input type="hidden" name="_csrf" value="<%= csrftoken %>">
  <input type="hidden" name="_method" value="Update">
  <input type="hidden" name="id" value="<%= id %>">
  <input type="submit" value="Update">
</form>

<p><a href="/">go back</a></p>
<% include ../footer %>

new

<% include ../header %>
<body>
 <h1>Add nnew</h1>
<form method="post" action="/posts/create">
  <input type="text" name="body">
  <input type="hidden" name="_csrf" value="<%= csrftoken %>">
  <input type="submit" value="add!">
</form>

<p><a href="/">go back</a></p>
<% include ../footer %>

show

<% include ../header %>
<body>
 <h1><%= post.title %></h1>
<p><%= post.body%></p>
<p><a href="/">go back</a></p>
<% include ../footer %>

header

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
</head>

footer

</body>
</html>

expressのgetとpost

expressはnode.jsのフレームワークです。npmでサーバー側にインストールして動かします。ここでは、getとpostの挙動をみましょう。

var bodyParser = require('body-parser');
var logger = require('morgan');
var express = require('express'),
 app = express();

app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');


// middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));

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);
});

 app.listen(3000);
 console.log("server starting...");

new.ejs


[nodemon] restarting due to changes...
[nodemon] starting `node app.js`
server starting...
GET /new 200 22.101 ms - 141
POST /create 200 1.023 ms - 5
GET /new 304 4.233 ms - -
POST /create 200 0.560 ms - 6

ブラウザです。
%e7%84%a1%e9%a1%8c