こんにちは、wattak777です。
必要に迫られREST APIを受け付けられるダミーサーバを作ることになりまして、出来るだけ手抜きで効率よく構築する手段はないものか、と構築しようとして手抜きの目論見がバレたのか少々ハマった話を展開しておきます。
当初LinuxをDockerかVirtualBoxに入れてやるか、と考えていたのですが、手持ちのPCがWindows 10だったためそれも使わずに出来ないものか、と色々探して出てきたのがこれ(google先生は本当に便利ですね)。
手持ちのPCがWindows 10が入っていたので、ここに書いてあるように、Node.jsをインストールし、npmでjson-serverを入れ、
{"API_test":{"param1":"Apple","param2":"Orange"}}
{"/api/test/mock/v1/API_test":"/API_test"}
これらを組み、
C:\work\Dummy_Rest> json-server db.json --routes route.json -p 12345
とすることで別途DOSプロンプトより
C:\test> curl http://localhost:12345/API_test
コールすると無事取れたのですが、問題はここから。
本来はLAN上の別のPCから取ってくる仕組みが欲しかったので、このページに書いてあったserver.jsをくみ上げ、
constjsonServer=require('json-server');constserver=jsonServer.create();constrouter=jsonServer.router('db.json');constmiddlewares=jsonServer.defaults();server.use(jsonServer.rewriter({"/api/test/mock/v1/API_test":"/API_test"}))server.use(middlewares);server.use(router);server.listen(12345,'192.168.1.1',()=>{console.log('Dummy REST API is running.');});
とやっていざ実行。
C:\work\Dummy_Rest> node server.js
module.js:472
throw err;
^
Error: Cannot find module 'json-server'
at Function.Module._resolveFilename (module.js:440:15)
at Function.Module._load (module.js:388:25)
at Module.require (module.js:468:17)
:(以下略)
ん?あれ?
で、色々調べてたら、コレがヒントに。
Cannot find module 'json-server' #454
要はnpmで取ってきたjson-serverのパスがNODE_PATHに当たっていなかったってことか。
ってことで、改めて環境変数を取ることに。
C:\work\Dummy_Rest> npm root -g
C:\Users\wattak\AppData\Roaming\npm\node_modules
C:\work\Dummy_Rest> set NODE_PATH=C:\Users\wattak\AppData\Roaming\npm\node_modules
その後 node
コマンドによる global.module.paths
で上記設定されたパスが入っていることを確認すると。。。
C:\work\Dummy_Rest> node server.js
Dummy REST API is running.
と、無事起動しましたとさ。
もちろん、node.exeに対してのファイアウォール設定は大丈夫ですよね?
これがないと、他のPCからC:\ClientPC> curl http://192.168.1.1:12345/API_test
とやってもつながらないのでお気をつけアレ。