1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

yarn + #Vue の #nuxt.js で axios-mock-server を利用して API リクエストする例

Last updated at Posted at 2020-05-05

ポイント/感想

2020/05/04

  • デフォルトの挙動?か何かで、設定してないはずのルーティングでも、てきとうに mock されてしまって、挙動を理解するまでしばらくかかった
  • nuxt で動くコード例が丸ごとあって助かった
  • axios経由で外部サイトへのリクエストもすべて mock されてしまうので、mock をやめる時に nuxt.config から plugin の記述を丸ごと削除した ( README などをちゃんと読んでいけば扱い方が分かるだろうけれど )
  • まだバージョンが1になっていない ( 0.16.3 )
  • すごく簡単なjsファイルを配置するだけで手軽にmockが利用できる
  • そもそものコンセプトのとおり、あくまで axios 経由での mock サーバーなので curl からのリクエストとか、他のモジュールを利用してのリクエストには使えないはず

Ref

m-mitsuhide/axios-mock-server: RESTful mock server using axios.

RESTfulな「axios-mock-server」の使い方 - Qiita

参考

この記事のとおりに作ったサンプルコード

公式で、nuxtでえ丸ごと動作するコード一式があったので、これを参考にした

やり方

nuxt プロジェクトを作る

yarn create nuxt-app my-project
cd my-project

必要なパッケージのインストール

yarn add axios
yarn add axios-mock-server --dev
yarn add @nuxtjs/axios

package.json

dev で起動 ( yarn dev ) する時に
同時に mock サーバーも起動するようにしておく

{
  "scripts": {
    "dev": "yarn mock:build && nuxt && yarn mock:watch",
    "mock:build": "axios-mock-server --build",
    "mock:watch": "axios-mock-server --watch"
  },
}

nuxt.config.js で module / plugins の設定をする

...
  plugins: [
    '~/plugins/mock.js'
  ],

  modules: [
    '@nuxtjs/axios',
  ],
...

plugins/mock.js

プラグインの読み込み用
axios と mock を関連付けるためのものっぽい

import mock from '~/mocks/$mock.js'

export default ({ $axios }) => {
  mock($axios)
}

mocks/$mock.js

yarn axios-mock-server --build で自動生成されるっぽい

/* eslint-disable */
import mockServer from 'axios-mock-server'
import mock0 from './users/_userId'

export default (client) => mockServer([
  {
    path: '/users/_userId',
    methods: mock0
  }
], client, '')

mocks/users/_userId.js

いちどデータを users の配列で作っている
この例だと id 0 のユーザー

value ( この例だとAPIのパスにふくまれるユーザーid ) に対応してユーザーデータを見つけてきて、データを返すということを、ものすごく簡潔な記述で出来るみたいだ

対応するデータを増やしたい場合は、配列のデータを増やせば良い

const users = [{ id: 0, name: 'foo' }]

export default {
  get({ values }) {
    return [200, users.find(user => user.id === values.userId)]
  }
}

pages/index.vue

設定した mock に axios 経由で リクエストするようにしておく

<template>
  <div class="container">
    <div>
      <h1 class="title">
        mock API
      </h1>
    </div>
    <div>
       {{ data }}
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  async asyncData ({ $axios, params }) {
    const data = await $axios.$get(`/users/0`)
    return { data }
  }
}
</script>

image

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?