LoginSignup
8
1

More than 3 years have passed since last update.

http-proxy-middleware を使用してダミーの API を用意

Last updated at Posted at 2019-09-07

http-proxy-middleware を使用してダミーの API を用意

サーバサイドで API が用意されてないから API 連携できない・・・という場合に
http-proxy-middleware によりダミーの API を用意します。

Nuxt.js 使ってます

スタブを用意

public な感じでアクセスできるところにスタブの JSON を用意します。
Nuxt.js なので static/stubs/ として用意します。

static/stubs/user.json
[
  {
    "id": 1,
    "name": "ROU"
  },
  {
    "id": 2,
    "name": "TK"
  },
  {
    "id": 3,
    "name": "JG"
  },
  {
    "id": 4,
    "name": "KNSRU"
  }
]

これでとりあえずどこからでも?アクセスできる JSON が用意されました。

http-proxy-middleware の設定

API としてアクセスしたい URL はだいたい /api/user/ などです。
そして実際に渡したいモノは static/stubs/user.json のレスポンスです。
そのようにアクセス可能となるよう設定をします。

nuxt.config.js ですが webpack.config.js などでもそう変わりはないはず・・・です

nuxt.config.js
const config = {
  ・・・
  proxy: {
    '/api/user': {
      target: 'http://localhost:3000/stubs',
      pathRewrite: {
        // /api/user/~ -> http://localhost:3000/static/stubs/user.json
        '^/api/user/': 'user.json',
      },
    },
  },
  ・・・
};
export default config;

実際に GET してみる

実際に axios などで取得してみます。

pages/index.vue
  mounted() {
    this.$axios.get('/api/user/').then(response => {
      console.log(response);
    });
  },

結果・・・

api-ppoi-response.jpg

4 名のユーザの情報が取得されました。
いかがでしたでしょうかいかがでしたでしょうか

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