復習がてら、Node.js+Expressで
以下のgifのようなサンプルを作りました。それについてメモ。
![]() |
|
ソース
index.pug
extends layout
block content
p こんにちは!#{userName}さん!
form(action='/' method='post')
p
| 名前:
input(type='text' name='userName')
p
input(type='submit' value='送信')
form(action='/deleteCookie' method='post')
input(type='submit' value='Cookieのリセット')
index.js
var express = require("express");
var router = express.Router();
router.get("/", function (req, res, next) {
if (req.cookies.name === undefined) {
res.render("index", { userName: "ゲスト" });
} else {
res.render("index", { userName: req.cookies.name });
}
});
router.post("/", function (req, res, next) {
res.cookie("userName", req.body.userName, {//Cookieの設定
maxAge: 60000,
httpOnly: false,
});
res.render("index", { userName: req.body.userName });
});
router.post("/deleteCookie", function (req, res, next) {
res.clearCookie("userName"); //Cookie削除
res.render("index", { userName: "ゲスト" });
});
module.exports = router;
Node.jsだけだと、これの3倍くらいの長さになりますよね。
備考
・本来は、routeフォルダで分けるべきですが、記事にする都合上すべてindex.jsに記載してます。
・express-generatorで作成したテンプレートを使っています。
・テンプレートエンジンはpugを使っています。
・Expressでcookieを使う場合は、app.jsでcookie-parserを設定しておかないとダメだし、cookie-parserの設定はapp.use('/', indexRouter);などのルーティングの前に書いておかないとダメ。
(express-generatorで作成した場合は、どちらもデフォルトで書かれています)
おわり

コメント