Lädt...

🔧 https://rb.gy/3jou1h


Nachrichtenbereich: 🔧 Programmierung
🔗 Quelle: dev.to

Node.jsでAPIサーバーを作成する

はじめに

Node.jsとExpressを使用して、シンプルなREST APIサーバーを作成する方法を紹介します。

必要な準備

Node.jsがインストールされていることを確認してください。次に、expressをインストールします。

npm init -y
npm install express

APIサーバーの作成

以下のコードで、基本的なGETとPOSTリクエストを処理するAPIを作成します。

const express = require('express');
const app = express();
const PORT = 3000;

app.use(express.json());

const tasks = [];

// タスクを取得
app.get('/tasks', (req, res) => {
    res.json(tasks);
});

// タスクを追加
app.post('/tasks', (req, res) => {
    const task = req.body;
    tasks.push(task);
    res.status(201).json(task);
});

app.listen(PORT, () => {
    console.log(`APIサーバーが http://localhost:${PORT} で起動しました`);
});

コードの説明

  1. express モジュールをインポート。
  2. app.use(express.json()) でJSONリクエストの解析を有効化。
  3. GET /tasks でタスク一覧を取得。
  4. POST /tasks で新しいタスクを追加。
  5. app.listen(PORT, () => {...}) でポート3000でAPIサーバーを起動。

APIの実行

以下のコマンドでサーバーを起動できます。

node server.js

ターミナルやPostmanで以下のリクエストを送信して動作を確認できます。

  • タスク一覧取得: GET http://localhost:3000/tasks
  • タスク追加: POST http://localhost:3000/tasks (JSONデータ付き)

まとめ

本記事では、Node.jsとExpressを使用して簡単なREST APIを作成しました。次回は、MongoDBを使用してデータを永続化する方法を紹介します。

...

🔧 https://rb.gy/3jou1h


📈 42.68 Punkte
🔧 Programmierung

🔧 Nginx force http to https On 443 https Port


📈 8.63 Punkte
🔧 Programmierung

🔧 HTTPS: How HTTPS Works - Handshake


📈 8.63 Punkte
🔧 Programmierung

📰 You like HTTPS. We like HTTPS. Except when a quirk of TLS can smash someone's web privacy


📈 8.63 Punkte
📰 IT Security Nachrichten

📰 HTTPS Explained: HTTP vs HTTPS and What You Should Know


📈 8.63 Punkte
🖥️ Betriebssysteme

📰 HTTPS-Interception: Sicherheitsprodukte gefährden HTTPS


📈 8.63 Punkte
📰 IT Nachrichten

📰 HTTPS-Interception: Sicherheitsprodukte gefährden HTTPS


📈 8.63 Punkte
📰 IT Security Nachrichten

🕵️ Firefox 83 released with 'HTTPS-Only Mode' that only loads HTTPS sites


📈 8.63 Punkte
🕵️ Hacking

🕵️ Stripo Inc: Unrestricted File Upload on https://my.stripo.email and https://stripo.email


📈 8.63 Punkte
🕵️ Sicherheitslücken

📰 How Does HTTPS Work to Keep Us Safe? (HTTP vs HTTPS Explained)


📈 8.63 Punkte
🖥️ Betriebssysteme

🕵️ https://www.honda-mideast.com/index.html


📈 4.31 Punkte
🕵️ Hacking

🕵️ https://covid19.padangpariamankab.go.id/heker


📈 4.31 Punkte
🕵️ Hacking

🕵️ https://ndugakab.jdihn.go.id/readme.php


📈 4.31 Punkte
🕵️ Hacking

🕵️ https://madc.mizoram.gov.in


📈 4.31 Punkte
🕵️ Hacking

🕵️ https://cco.mesquita.rj.gov.br/kurd.html


📈 4.31 Punkte
🕵️ Hacking

matomo