次の記事を参考にしました。
Node+TypeScript+ExpressでAPIサーバ構築
- package.json を作成
- typescript のインストール
- tsconfig.json を作成
- express をインストール
- package.json を編集
- index.ts を作成
- サーバーの起動
- クライアントで確認
- Httpie で確認
npm init -y
npm install -D typescript @types/node
./node_modules/.bin/tsc --init
npm install -D ts-node
npm install express
npm install -D @types/express
package.json
(省略)
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"tsc": "tsc",
"ts-node": "ts-node"
},
(省略)
index.ts
import express from 'express'
const app: express.Express = express()
// CORSの許可
app.use((req, res, next) => {
res.header("Access-Control-Allow-Origin", "*")
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
next()
})
// body-parserに基づいた着信リクエストの解析
app.use(express.json())
app.use(express.urlencoded({ extended: true }))
// GetとPostのルーティング
const router: express.Router = express.Router()
router.get('/get_test', (req:express.Request, res:express.Response) => {
const str_out:string = "Hello " + req.query.name + "\n"
res.send(str_out)
})
router.post('/post_test', (req:express.Request, res:express.Response) => {
const str_out:string = "Morning " + req.query.name + "\n"
res.send(str_out)
})
app.use(router)
// 3000番ポートでAPIサーバ起動
app.listen(3000,()=>{ console.log('Example app listening on port 3000!') })
npm run ts-node index.ts
$ curl http://localhost:3000/get_test?name=John
Hello John
$ curl http://localhost:3000/get_test?name=Mary
Hello Mary
$ curl -X POST http://localhost:3000/post_test?name=John
Morning John
$ curl -X POST http://localhost:3000/post_test?name=Mary
Morning Mary
http :3000/get_test name==John
http :3000/get_test name==Mary
http POST :3000/post_test name==John
http POST :3000/post_test name==Mary
確認したバージョン
$ node --version
v20.2.0
$ npm --version
9.6.6