0
1

More than 1 year has passed since last update.

express-generator で簡単な WebAPI を作成

Last updated at Posted at 2022-02-02

こちらと同じことを、express-generator で行ってみます。
Express で簡単な WebAPI を作成

ex01 というフォルダーで作業します。

プロジェクトの作成

npx express-generator

依存関係をインストール

npm install

サーバーの起動

DEBUG=ex01:* npm start

クライアントで http://localhost:3000/users にアクセスして GET の API の動作を確認

$ http http://localhost:3000/users
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 23
Content-Type: text/html; charset=utf-8
Date: Wed, 02 Feb 2022 00:23:08 GMT
ETag: W/"17-dz3lQFWsvaILP0XWy2YesfdbyNA"
Keep-Alive: timeout=5
X-Powered-By: Express

respond with a resource

app.js を改造 (2行追加)

app.js
省略
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var sumRouter = require('./routes/sum');   // 追加
省略
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/sum', sumRouter);   // 追加
省略

routes/sum.js を作成

routes/sum.js
var express = require('express')
var router = express.Router()

/* GET users listing. */
router.get('/', function(req, res, next) {
    res.send('respond from sum')
})

router.post('/', function(req, res, next) {
    var aa = 0
    var bb = 0

    if (req.body.aa) {
        aa = parseInt(req.body.aa,10)
        }

    if (req.body.bb) {
        bb = parseInt(req.body.bb,10)
        }

    var param = {}
    param["aa"] = aa
    param["bb"] = bb
    param["sum"] = aa + bb
    param["diff"] = aa - bb

    res.header('Content-Type', 'application/json; charset=utf-8')
    res.send(param)
})


module.exports = router

サーバーを起動して、クライアントでテスト

$ http POST http://localhost:3000/sum aa=12 bb=34
HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 37
Content-Type: application/json; charset=utf-8
Date: Wed, 02 Feb 2022 00:28:27 GMT
ETag: W/"25-ZP0Ow8AEz9vFH1ytAhkzjJL7RF8"
Keep-Alive: timeout=5
X-Powered-By: Express

{
    "aa": 12,
    "bb": 34,
    "diff": -22,
    "sum": 46
}
0
1
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
0
1