備忘録

備忘録

TypeScript + ExpressでHelloWorldする方法

Ⅰ. はじめに

タイトルの通り「expressでHelloWorldする方法」です。

Ⅱ. 手順

1. 必要なパッケージをインストールする
npm install express
npm install --save-dev ts-node @types/express
2. ファイルを編集する

package.json

"scripts": {
+  "start": "ts-node src/app.ts"
}

tsconfig.json

{
  "compilerOptions": {
    "moduleResolution": "node"
  }
}
3. サンプルプログラムを書く

src/app.ts

import * as express from 'express'

const app = express()
app.use(express.json())
app.use(express.urlencoded({ extended: true}))
app.disable('x-powered-by')

app.get('/test1', async (req, res) => {
  res.send('hello world')
})

app.get('/test2', async (req, res) => {
  res.send(`hello ${req.query.name}`)
})

app.post('/test3', async (req, res) => {
  const name = req.body.name
  res.send(`hello ${name}`)
})

app.get('/test4', async (req, res) => {
  res.send({
    'id': 1,
    'name': 'tanaka',
    'ban': false
  })
})

const port = 3000
app.listen(port, () => console.log(`Server listening on port ${port}`))

実行結果

GET http://127.0.0.1:3000/test1 HTTP/1.1

HTTP/1.1 200 OK
hello world
GET http://127.0.0.1:3000/test2?name=tanaka HTTP/1.1

HTTP/1.1 200 OK
hello tanaka
POST http://127.0.0.1:3000/test3 HTTP/1.1
Content-Type: application/json
Content-Length: 20

{ "name": "tanaka" }

HTTP/1.1 200 OK
hello tanaka
POST http://127.0.0.1:3000/test3 HTTP/1.1
Content-Type: application/x-www-form-urlencoded
Content-Length: 11

name=tanaka

HTTP/1.1 200 OK
hello tanaka
GET http://127.0.0.1:3000/test4 HTTP/1.1

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8

{"id":1,"name":"tanaka","ban":false}

express代替

ts-node代替

  • vite-node