やりたいこと
node.jsで動くWebAPIモックサーバーのmockyを使って、
{ "name": "John Smith" }
をPOSTリクエストしたら
{
"id": 1,
"name": "John Smith"
}
が返却され、
{ "name": "Taro Yamada" }
をPOSTリクエストしたら
{
"id": 1,
"name": "Taro Yamada"
}
が返却されるように、リクエストの内容をレスポンスに反映したかったのだが、つまづいたのでメモを残す。
mockyのインストール方法、基本の使い方はGithubのREADMEを参考にしてください。
結論
基本の使い方は公式のREADMEといいつつ、mocky自体かなりメンテされていないみたいなので少し書き方は今風にしてる箇所もあるが基本的に一緒。
mock.js
const mocky = require('mocky');
mocky.createServer([
{
url: '/users',
method: 'POST',
res: (req, res, callback) => {
const params = JSON.parse(req.body);
callback(null, {
status: 201,
body: JSON.stringify(
{
"id": 1,
"name": params.name
}
)
});
}
}
]).listen(4321);
JSON.parse
でリクエストのjsonをパースしてあげないとうまく変数を抽出できなかったり、JSON.stringify
でjson形式で書いたレスポンスをstring型に変換しないとうまく動作しない。(ここでつまづいた...😢)
特にJSON.stringify
を忘れたために、
_http_outgoing.js:670
throw new ERR_INVALID_ARG_TYPE('first argument',
^
TypeError [ERR_INVALID_ARG_TYPE]: The first argument must be of type string or an instance of Buffer. Received an instance of Object
at write_ (_http_outgoing.js:670:11)
at ServerResponse.write (_http_outgoing.js:638:15)
at sendRes (/app/node_modules/mocky/lib/mocky.js:166:9)
at /app/node_modules/mocky/lib/mocky.js:74:10
at Timeout._onTimeout (/app/mocky.js:16:9)
at listOnTimeout (internal/timers.js:549:17)
at processTimers (internal/timers.js:492:7) {
code: 'ERR_INVALID_ARG_TYPE'
}
というエラーが出続けて泣いた😿
動作確認
これでcurlで確認すればうまくいくはず。
$ curl -X POST 'http://localhost:4321/users' -d '{ "name": "John Smith" }'
{"id":1,"name":"John Smith"}
みにくいのでpython -m json.tool
をパイプで渡すと見やすくなる。
$ curl -X POST 'http://localhost:4321/users' -d '{ "name": "John Smith" }' | python -m json.tool
{
"id": 1,
"name": "John Smith"
}