メッセージングフォームの作成

18686 ワード

開発環境の設定


まず、開発環境を構築しなければならない.visualstudio codeでは、npm initを使用してデフォルト環境を作成します.
その後、npm i express socket.io expressおよびsokcetを通過する.ioをインストールします.
デフォルトではノードです.jsで実行するサーバを作成します.
const express = require('express');

const app = express();

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.get('/', (req, res, next) => {
  res.send('<h1>Hello, world!</h1>');
});

app.use((err, req, res, next) => {
  console.error(
    `message: ${err.message}, status: ${err.status}`
  );
  res.status(err.status || 500).json({
    message: err.message,
    status: err.status
  });
});

app.listen(3000, () => {
  console.log(`Server listing at 3000 port!`);
});

合成HTML


注意!このプロジェクトを行う開発者は、フロントエンドの経験がないため、コードが汚れ、構造が不合理になる可能性があります.
Get started | Socket.IO
socket.io公式サイトのファイルに従って作成することにしました.まだよくわからないので、まずはチュートリアル感覚で行います.
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <link rel="stylesheet" href="/css/style.css">
  <title>Real-time chat application in Node.js</title>
</head>
<body>
  <ul id="messages"></ul>
  <form id="form" action="">
    <input id="input" autocomplete="off">
    <button>Send</button>
  </form>
</body>
</html>
でも公式チュートリアル(?)styleもhtmlで作成されているようなので、cssファイルに移動したいです.

cssファイルの作成

body {
  margin: 0;
  padding-bottom: 3rem;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Helvetica, Arial, sans-serif;
}

#form {
  background: rgba(0, 0, 0, 0.15);
  padding: 0.25rem;
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  height: 3rem;
  box-sizing: border-box;
  backdrop-filter: blur(10px);
}

#input {
  border: none;
  padding: 0 1rem;
  flex-grow: 1;
  border-radius: 2rem;
  margin: 0.25rem;
}

#input:focus {
  outline: none;
}

#form > button {
  background: #333;
  border: none;
  padding: 0 1rem;
  margin: 0.25rem;
  border-radius: 3px;
  outline: none;
  color: #fff;
}

#messages {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

#messages > li {
  padding: 0.5rem 1rem;
}

#messages > li:nth-child(odd) {
  background: #efefef;
}
正式なチュートリアルのstyleをそのままcssに移すと、以下の内容が見えます(ただし、先端や凧がないので、それが何を意味しているのかしか分かりません).

合成したHTMLページを表示


これで、作成したHTMLページがサーバが開いたときに表示されることを確認する必要があります.app.jsに次のコードを追加します.
app.get('/', (req, res, next) => {
  res.sendFile(__dirname + '/public/index.html');
});
ただし、このコードのみを記述する場合はindexです.htmlファイルのみが表示され、cssファイルで作成したスタイルは適用されません.サーバは、express.static()メソッドを呼び出して静的ファイルを処理する(もちろん、上記のルーティングの前に記述する必要がある).
app.use(__dirname + '/public');

実行結果



下部にメッセージ転送フォームが表示され、スタイルが良好に適用されていることがわかります.