4
3

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 1 year has passed since last update.

TypeScript で Express を使う

Last updated at Posted at 2020-10-14

次の記事を参考にしました。
Node+TypeScript+ExpressでAPIサーバ構築

  1. package.json を作成
  2. npm init -y
    
  3. typescript のインストール
  4. npm install -D typescript @types/node
    
  5. tsconfig.json を作成
  6. ./node_modules/.bin/tsc --init
    
  7. express をインストール
  8. npm install -D ts-node
    npm install express
    npm install -D @types/express
    
  9. package.json を編集
  10. package.json
    (省略)
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "tsc": "tsc",
        "ts-node": "ts-node"
      },
    (省略)
    
  11. index.ts を作成
  12. 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!') })
    
  13. サーバーの起動
  14. npm run ts-node index.ts
    
  15. クライアントで確認
  16. $ 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
    
  17. Httpie で確認
  18. 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
4
3
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?