LoginSignup
0

More than 3 years have passed since last update.

JSON Serverを利用してみる

Last updated at Posted at 2020-07-18

json-server をインストール

$ npm install -g json-server

json ファイルを用意する

{
    "data" : [
        {
            "id": 1,
            "name": "apple",
            "price": 100
        },
        {
            "id": 2,
            "name": "orange",
            "price": 200
        }
    ]
}

json を登録する

$ json-server list.json

  \{^_^}/ hi!

  Loading list.json
  Done

  Resources
  http://localhost:3000/data

  Home
  http://localhost:3000

http://localhost:3000/data にアクセスすると json が返る。


POSTリクエストに対してresponseを返す

  • middleware を咬ませて GET と見せかける。
middleware.js
 module.exports = function (req, res, next) {
  if (req.method === 'POST') {
      req.method = 'GET' // GETに偽装
      // req.url += '_post' // アクセス先をPOST用に変更
  }
  next()
}
  • 起動する
$ json-server -w db.json -m middleware.js

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