LoginSignup
0
0

More than 1 year has passed since last update.

json-server tips

Last updated at Posted at 2023-02-08

json-serverとは何?

expressベースのAPIモックサーバーです。
通常のAPIモックサーバーとしてJSONを定義するだけで簡単に使えます。
また、DBを内蔵しており、POSTなどの更新にも対応しているようです(未使用)
追記:直接、db.jsonを書き換えるようです。

例えば以下のようなJSONファイルを用意するだけでモックサーバーが簡単に作れます。

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

CLIで以下のコマンドを叩くことでモックサーバーが起動します。

$ json-server --watch db.json

但し、後述しますが、CLIにはバグがあるため、モジュールを書くのが無難です。

Tips

複数階層のルートを指定したい

そのままだと指定できないため、rewriterを利用して、リクエストがあったルートを書き換えます。
例:/hoge/barへのアクセスを/barへ流す

server.use(jsonServer.rewriter({
  "/hoge/bar": "/bar",
}))

POSTメソッドなどでJSONを返却したい

そのままだと更新系APIとして動作してしまうため、midddlewareでGETメソッドへ置き換えます。

server.use(middlewares)

server.use((req, res, next) => {

  if (req.method === 'POST') {
    req.method = 'GET';
  }
  next();
});

CLIからmiddlewareを指定しても機能しない

公式にもサンプルが載っているのにCLIからはバグで使えません。
モジュールを書く必要があります。

0
0
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
0