LoginSignup
2
2

More than 3 years have passed since last update.

axios-mock-adapterで動的なurlのリクエストを取得する方法

Last updated at Posted at 2020-09-01

axios-mock-adapterで動的なurlのリクエストを取得する方法

URLの末尾にパラメータがはいるリクエストの場合

/hoge/piyo/0123456789
/hoge/piyo/9876543210

リクエスト投げる側

export default {
 data() {
    return {
      fuga:null, // fugaが可変
    };
  },
    mounted() {
       this.$axios.get("/hoge/piyo/",{ params: { fuga: this.fuga} })
           .then((response) => {
               console.log(responce)
            })
           .catch((e) => {
               console.log(e)
           });
         });
    }
}

mock


export default {

  mock.onGet('/hoge/piyo/').reply(config => {
       if(config.params.fuga == '0123456789') {
         res = 'param1'
        }
        if(config.params.fuga == '1234567890') {
         res = 'param2'
        }
        return [200, res]
      }),
}

URLの途中にパラメーターが入るようなリクエストの場合

/hoge/0123456789/piyo
/hoge/9876543210/piyo

リクエスト投げる側

export default {
 data() {
    return {
      fuga:null, // fugaが可変
    };
  },
    mounted() {
       this.$axios.get("/hoge/" + this.fuga + "/piyo")
           .then((response) => {
               console.log(responce)
            })
           .catch((e) => {
               console.log(e)
           });
         });
    }
}

mock


function checkRequestUrl(path = '') {
  // ":"から始まる単語構成文字(a-zA-Z_-^9)を"/"を含まない文字列を許容するように置換する
  path = typeof path === 'string'
    ? new RegExp(path.replace(/:\w+/g, '[^/]+'))
    : path
  return path
}

export default {
  checkRequestUrl,
  mock.onGet(checkRequestUrl('/hoge/:fuga/piyo')).reply(config => {
        // パラメータを取得してパラメータごとに返却値を変更する
        var params = config.url.match(/\/hoge\/(.+)\/piyo/);
        let res = ''
        if(params[1] == '0123456789') {
         res = 'param1'
        }
        if(params[1] == '1234567890') {
         res = 'param2'
        }
        return [200, res]
      }),
}

参考

How to mocking a http request with route params using axios-mock-adapter

2
2
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
2
2