3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Express.jsとPostgreSQLを使った基本的なサーバー構築

Last updated at Posted at 2024-07-14

Express.jsとPostgreSQLを使った基本的なサーバー構築

この記事では、Node.jsのフレームワークであるExpress.jsを使用して基本的なサーバーを構築し、PostgreSQLデータベースと連携する方法を紹介します。静的ファイルの提供、データの取得、データの送信方法について解説します。

napkin-selection (20).png

必要なnpmパッケージ

npm install express pg

使用するnpmパッケージ
express: Node.js用のウェブフレームワークで、サーバーの構築に使用します。
pg: Node.js用のPostgreSQLクライアントで、データベース接続に使用します。

PostgreSQLデータベースに接続するための設定を行います。

const { Pool } = require("pg");

const pool = new Pool({
  user: "your_db_user",
  host: "localhost",
  database: "your_db_name",
  password: "your_db_password",
  port: 5432,
});

module.exports = {
  query: (text, params) => pool.query(text, params),
};

サーバー設定 (server.js)
以下のコードをserver.jsに追加し、Expressサーバーを設定します。

const express = require("express");
const path = require("path");
const DB = require("./db/db");
const app = express();
const port = 5000;

app.use(express.json());
app.use(express.static("./public"));

// ルートエンドポイントでindex.htmlを提供
app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "public", "index.html"));
});

// データベースからユーザーデータを取得
app.get("/new", async (req, res) => {
  try {
    const result = await DB.query("SELECT * FROM users;");
    console.log(result.rows);
    res.json(result.rows);
  } catch (error) {
    console.error("エラーが発生", error);
    res.status(500).send("エラー発生");
  }
});

// フォームデータの受け取り
app.post("/submit", (req, res) => {
  const { name, email, message } = req.body;
  console.log(name);
  console.log(email);
  console.log(message);
  res.send("データ獲得");
});

Postmanを使用して、 http://localhost:5000/submit にPOSTリクエストを送り、データがコンソールに出力されることを確認します。

【まとめ】

Express.jsとPostgreSQLを使用して基本的なサーバーを構築する方法について紹介しました。静的ファイルの提供、データベースからのデータ取得、フォームデータの受け取り方法についても解説しました。

3
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?