見出し画像

【Vue.js+axios】Query parametersとPath parameters

※整理できてないので修正あり


クエリパラメータ

ex. POSTリクエスト

連想配列のdataにキーと値を格納して、それをaxios.post()の第二引数に指定

(new FormDataなどでappendしたものでも可能)

const data = { name: 'hoge' };  // 該当パラメータ
await axios
   .post('/api/sample/', data) // 第一引数にエンドポイント、第二引数にクエリパラメータ(上記)
   .then(res => {
       alert("「" + data.name + "」登録完了");
       this.$router.push({path: '/articles/list'});
   })
   .catch(error => {
       alert("「" + data.name + "」登録失敗");
       console.log(error, data);
   });

クエリパラメータをセットする場合は、URLに直接記述するか、第2引数にparamsというキー名でセットする

追記_20220111:axiosで送信したパラメータをFastAPI側で取得する

# paramsフィールドとして送信した場合
@app.get("/endpoint")
async def get_param(request: Request, db: Session = Depends(get_db)):
  paramValue = request.query_params['key']
  
  
# FormDataオブジェクトとして送信した場合
@app.get("/endpoint")
async def get_param(request: Request, db: Session = Depends(get_db)):
  form = await request.form()
  paramValue = form['keys']

パスパラメータ

パスパラメータでも可変的に(変数で)エンドポイントを動的指定できる

ex. GETリクエスト

コンポーネントのdata()オプション内の shop_id プロパティ変数の値をパスにくっつけている例

methods:{
// コンポーネントのdata()オプションから取得したパラメータを渡すパターン
hoge_func:async function(){
let axiosInstance = axios.create({
       'headers': {'Content-Type': 'multipart/formdata'}
     })
await axiosInstance
.get(
     'http://localhost:8000/api/v1/shops/' + this.shop_id
   );
}
// 外部(呼び出し元)から引数を受け取るパターン
fuga_func:async function(shop_id){
let axiosInstance = axios.create({
       'headers': {'Content-Type': 'multipart/formdata'}
     })
await axiosInstance
.get(
     'http://localhost:8000/api/v1/shops/' + shop_id
   );
}

この記事が気に入ったらサポートをしてみませんか?