83
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

expressの開発にTypeScriptを利用する

Last updated at Posted at 2021-02-09

expressをTypescriptで開発する方法のメモ。
nodeをTypeScriptで利用する基本的方法はこちらをどうぞ。

準備

場所の準備

mkdir ts-express-test
cd ts-express-test

必要なモジュールのインストール(Typescript使うため)

tsc, ts-nodeをインストールして、tsconfig.jsonも生成しておきます。

npm init -y

npm install -D typescript
npm install -D @types/node
npm install -D ts-node

npx tsc --init

expressのインストール

expressとtypesをインストールします。

npm install express
npm install -D @types/express

実装

色々実装です。とりあえず実装用のファイルを作成。

touch index.ts

index.tsに以下の記述をします。とりあえずGETだけ実装。
ここで利用したAPIを再利用。

index.ts
import express from 'express'
const app: express.Express = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

//CROS対応(というか完全無防備:本番環境ではだめ絶対)
app.use((req: express.Request, res: express.Response, next: express.NextFunction) => {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "*")
    res.header("Access-Control-Allow-Headers", "*");
    next();
})

app.listen(3000, () => {
    console.log("Start on port 3000.")
})

type User = {
    id: number
    name: string
    email: string
};

const users: User[] = [
    { id: 1, name: "User1", email: "user1@test.local" },
    { id: 2, name: "User2", email: "user2@test.local" },
    { id: 3, name: "User3", email: "user3@test.local" }
]

//一覧取得
app.get('/users', (req: express.Request, res: express.Response) => {
    res.send(JSON.stringify(users))
})

実行と動作確認

では動作確認。

実行

expressの実行は下記の通り。

npx ts-node index.ts

とりあえずcurlで動作確認。

curl -s -X GET http://localhost:3000/users | python -mjson.tool

[
    {
        "email": "user1@test.local",
        "id": 1,
        "name": "User1"
    },
    {
        "email": "user2@test.local",
        "id": 2,
        "name": "User2"
    },
    {
        "email": "user3@test.local",
        "id": 3,
        "name": "User3"
    }
]
83
63
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
83
63

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?