LoginSignup
6
3

More than 3 years have passed since last update.

JSON Serverでオブジェクト以外を返す方法

Posted at

JSON Serverで文字列を返す方法

公式のGetting startedをもとに、
/profileにリクエストが来た場合、nameの値を文字列として返却する方法を紹介する。
文字列として返したい箇所には、"type": "string"を記載している。

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

以下のように、JSON Serverをモジュールとして使用することで、上記内容を返却する前に後処理を行えるようにする。

server.js
const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('db.json')
const middlewares = jsonServer.defaults()

// Middleware(前処理)
server.use(middlewares)
server.use((req, res, next) => {
    // 受け取ったリクエストに前処理を行う場合はここに書く
    // POSTをGETに変換する例
    if (req.method === 'POST') {
        req.method = 'GET'
    }
    // リクエストURLを書き換える例
    req.url = req.url.replace(/\./g, "")
    console.log(req.url)
    next()
})

// ルーティングを使用する場合はここに書く
server.use(jsonServer.rewriter({
    "/api/*": "/$1",
    "/posts\\?id=:id": "/posts/:id",
}))
server.use(router)

// 後処理
router.render = function (req, res) {
    // レスポンスに後処理を行う場合はここに書く
    // db.jsonの返却値に"type":"string"がある場合、nameの値を文字列として返却する例
    if (res.locals.data.type && res.locals.data.type === 'string') {
        res.send(res.locals.data.name)
    } else { // それ以外はdb.jsonに記載したとおり返却する
        res.send(res.locals.data)
    }
}

// モックサーバ起動
server.listen(3000, () => {
    console.log('JSON Server is running')
})

あとは、nodeコマンドで実行する

$ node server.js

参考

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