LoginSignup
3
2

More than 1 year has passed since last update.

Node.js/Express+TypeScriptでWeb API作成

Last updated at Posted at 2021-09-14

はじめに

Node.js + Express + TypeScript を使用して Web API を作成する。Express を扱うのは始めてのため、公式サイトを参考に進める。実行環境は以下。

  • Node.js: 14.17.6
  • npm: 6.14.15
  • Express: 4.17.1
  • TypeScript: 4.4.3

TypeScript 環境の作成

まず TypeScript 環境を作成する。

$ npm init -y
$ npm install -D typescript @types/node ts-node
$ npx tsc --init

Express のインストール

つづいて Express とその型定義をインストールする。

$ npm install express
$ npm install -D @types/express

Hello World Example

以下コードで簡単な実行を試すことができる。

app.ts
import express from 'express';

const app = express();
const port = 3000;

app.get('/', (req, res) => {
  res.send('Hello World!');
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

実行確認

上記で作成した app.ts を実行する。

$ npx ts-node app.ts
Example app listening at http://localhost:3000

別のターミナルを立ち上げて以下コマンドを実行すると、Hello, World! が返ってくることが確認できる。

$ curl http://localhost:3000

おわりに

公式チュートリアルにしたがって、Express の実行を確認した。より詳細な理解を行うため、上記で作成したプログラムではなく、すでにひな形として準備されている express-generator や TypeScript 用に作成されている express-generator-typescript も試してみたい。

3
2
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
2