こんにちは、なかにしです。
引き続きExpressやてくよ~
IDによって遷移先を変更する
ID:0→ようこそ田中さん!
ID:1→ようこそ中西さん!
的なことをやっていきます。
const express = require("express");
const app = express();
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
// ミドルウェアを作る
app.param("id", function (req, res, next, id) {
  const name = ["田中", "中西", "水谷"];
  
  // idによってnameを変更
  req.params.name = name[id];
  next();
});
app.get("/", function (req, res) {
  res.render("index", { title: "たーいとる" });
});
app.get("/:id", function (req, res) {
  res.render("index", { title: `ようこそ: ${req.params.name}さん!` });
});
app.listen(8000, console.log("Nice Server~"));<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <h1>んんん</h1>
    <p>よぉ!</p>
    <p>
      <%= title %>
    </p>
  </body>
</html>予め名前の一覧を用意しておき、IDによって取得する名前を変えました。
これで「id」に「0」がきたときは「田中」、「1」がきたときは「中西」が表示されます。
この「req.params.name = name[id]」の部分を
DBからデータを取得する処理にすればうまく連携できそうですね~
動作確認


POSTでデータを受け取る
フォームで飛ばしたPOSTデータを処理します。
まずフォームを作っていきます。
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <h1>トップページ</h1>
    <p>フォームは<a href="/contact">こちら</a></p>
  </body>
</html><!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
  </head>
  <body>
    <h1>フォームじゃい</h1>
    <form action="/create" method="post">
      <label>
        名前
        <input type="text" name="name" />
      </label>
      <label>
        パスワード
        <input type="text" name="password" />
      </label>
      <input type="submit">
    </form>
  </body>
</html>const express = require("express");
const app = express();
app.set("views", __dirname + "/views");
app.set("view engine", "ejs");
app.get("/", function (req, res) {
  res.render("index");
});
app.get("/contact", function (req, res) {
  res.render("form");
});
app.post("/create", function (req, res) {
  // データ取り出して処理
});
app.listen(8000, console.log("Nice Server~"));「/」でトップページ(index.ejs)を表示、
そこからaタグで「/contact」に飛ばし、フォームが書かれた「form.ejs」を表示しています。
フォームから「/create」にPOSTでデータを飛ばし、処理していく算段です。
これをやっていこうと思ったのですが、
どうせならWebアプリ化してPUTもDELETEも一気にやります。(優柔不断)
次回からミニアプリ作っていきます🙌



