🖥

Nuxt.js + Vue + axios でURLのid (パスパラメータ) を利用してhttpリクエストする例

に公開
  • nuxtの命名規則にのっとって pages/<page_name>/_id.vue などという名前でファイルを作る
  • ブラウザで /path-parameter-id/1 にアクセスして動作確認する
  • axios で は、URL のパスパラメータを利用して、外部サイトにリクエストする

File

pages/path-parameter-id/_id.vue

<template>
  <div>
    <h1>
      Path parameter id
    </h1>
    <h2>ID</h2>
    <div>
      {{ path_parameter_id }}
    </div>
    <h2>httpbin reponse</h2>
    <div>
      {{ response }}
    </div>
  </div>
</template>

<script>
import axios from 'axios'

export default {
  async asyncData ({ $axios, params }) {
    const path_parameter_id = `${params.id}`
    const response = await $axios.$get(`https://httpbin.org/get?id=${path_parameter_id}`)

    return { path_parameter_id, response }
  }
}
</script>

http://localhost:3000/path-parameter-id/1

httpbinを利用してお手軽に動作確認可能

httpbin というサービスのAPIの仕様で
リクエスト先のURLがレスポンスに含まれて返ってくる "url": "https://httpbin.org/get?id=1"

image

Original by Github issue

https://github.com/YumaInaura/YumaInaura/issues/3133

チャットメンバー募集

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

https://line.me/ti/g2/eEPltQ6Tzh3pYAZV8JXKZqc7PJ6L0rpm573dcQ

Twitter

https://twitter.com/YumaInaura

公開日時

2020-05-05

Discussion