LoginSignup
1

More than 3 years have passed since last update.

json-server で使い捨てモックサーバを作る

Posted at

フロントエンド開発に必要となったため json-server で
使い捨てモックサーバを構築する。

■json-server
https://github.com/typicode/json-server

インストール

mkdir /tmp/$(date +%Y%m%d)_moc && cd /tmp/$(date +%Y%m%d)_moc
yarn add json-server

初期設定

touch /tmp/$(date +%Y%m%d)_moc/db.json
touch /tmp/$(date +%Y%m%d)_moc/routes.json
touch /tmp/$(date +%Y%m%d)_moc/middlewares.js

データを用意する

db.json
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}

パスを追加する

■参考
https://github.com/typicode/json-server#add-custom-routes

routes.json
{
  "/api/v1/*": "/$1",
  "/api/v2/posts": "/posts",
  "/api/v3/comments": "/comments",
  "/api/v4/profile": "/profile"
}

GET以外のリクエストだとdb.jsonが書き換えられてしまうので、
全てのリクエストをGETにする

■参考
https://github.com/typicode/json-server#add-middlewares

middlewares.js
module.exports = function (req, res, next) {
  req.method = 'GET'
  req.query = req.body
  next()
}

サーバ起動

/tmp/$(date +%Y%m%d)_moc/node_modules/.bin/json-server --routes routes.json --watch db.json --middlewares middlewares.js -p 3000

curlコマンドで試してみる

curl http://localhost:3000/posts
curl http://localhost:3000/api/v1/posts

出力結果

[
  {
    "id": 1,
    "title": "json-server",
    "author": "typicode"
  }
]

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
1