Angular でモックを作るなら ... 次の3つが浮かびます。
・1. Angular in-memory-web-api
参考: https://bit.ly/35iW0SN
・2. json-server
・3. HttpClientTestingModule
・2. json-server を作成してみます。
npm i -D json-server
ファイル名は任意のファイル名でokですが、とりあえず db.json ファイルを新規作成します。
vi db.json
db.json を以下の内容で保存します。
{
"users": [
{
"id": 1,
"title": "お名前太郎",
},
{
"id": 2,
"title": "サンプル花子",
},
{
"id": 3,
"title": "検索太郎",
}
]
}
( package.json がない場合はこちらを実行 )
npm init
package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
↓
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1" ,
"json-server": "json-server --watch ./db.json --port 9999"
},
npm run json-server
http://localhost:9999/ で json-server へアクセスすることができます。
npx json-server db.json -m middleware.js --watch --host 0.0.0.0 --port 9999
ホストに 0.0.0.0 を指定することで http://localhost:9999/ と http://ローカルIPアドレス で json-server へアクセスすることができます。
http://localhost:9999/contents
http://localhost:9999/contents/1
にアクセスして戻り値を確認します。
postmanを使って次のようにPOSTします。
postすると自動で db.json のファイルが更新されます。
db.json ファイルを更新しないようにするには
db.js
const db = require('./db.json')
module.exports = () => db
package.json
"json-server": "json-server db.js --port 9999"
とすると、確かにjson-serverは更新されますが、メモリ上のみの更新なので db.json は更新されません。(再起動すると元のデータに戻ります。)
また、「ミドルウェアを使ってPOSTメソッドをGETメソッドに変換する」という技も有効ですのでそちらでもOKです。
middleware.js
module.exports = function (req, res, next) {
if (req.method === 'POST') {
req.method = 'GET'
req.query = req.body
}
next()
}