簡體   English   中英

axios中傳遞路徑參數

[英]Passing path parameters in axios

我將 Axios 與 NodeJs 一起使用,並嘗試在axios.get()方法中傳遞路徑參數。 例如,如果 URL 是url = '/fetch/{date}' ,我想在調用axios.get(url)時將{date}替換為實際日期。

Github和StackOverflow上的源碼都翻了一遍,沒找到方法。

有沒有可能在實際調用Axios的get方法的時候,保留帶參數的url作為占位符替換掉?

使用模板字符串

    url = `/fetch/${date}`

或者只是標記它

    url = '/fetch/'+ date

Axios 沒有這個功能,看起來團隊不想添加它

感謝以前的響應者的靈感,對我來說,這似乎是最接近您(和我)正在尋找的解決方案:

1 - 要存儲所有 URL 及其參數的位置,將它們定義為使用模板字符串返回組合 URL 的函數:

export var fetchDateUrl = (date) => `/fetch/${date}`;

如果您需要對連接到 URL 中的值進行任何特定於類型的格式化,這個函數是一個很好的地方。

2 - 在您要發出請求的地方,使用正確的參數調用函數:

import { fetchDateUrl } from 'my-urls';
axios.get(fetchDateUrl(someDateVariable))...;

另一種變體,如果你真的喜歡在調用站點命名參數的想法,你可以定義 URL 函數來解構這樣的對象:

var fetchDateUrl = ({date}) => `/fetch/${date}`;

然后你會像這樣使用它:

axios.get(fetchDateUrl({date: someDateVariable}));

鑒於某些 API /fetch/${date}您可能希望將 axios 調用包裝在一個函數中。

const fetchData = (date) => axios.get(`/fetch/${date}`);

fetchData(dateObject.toFormat('yyyy-mm-dd'))
  .then(result => { ... });

但是,這需要調用代碼正確格式化date 您可以通過使用處理日期字符串解析並在函數中執行格式強制的 DateTime 庫來避免這種情況。

const fetchData = (date) => axios.get(`/fetch/${date.toFormat('yyyy-mm-dd')}`);

fetchData(dateObject)
  .then(result => { ... });

您可以使用模板字符串,即:

let sellerId = 317737

function getSellerAnalyticsTotals() {
    return axios.get(`http://localhost:8000/api/v1/seller/${sellerId}/analytics`);
}

我認為使用 axios 攔截器更好地做到這一點:

//create your instance
const instanceAxios = axios.create({
  baseUrl: 'http://localhost:3001'
]);

instanceAxios.interceptors.request.use(config => {
    if (!config.url) {
        return config;
    }

    const currentUrl = new URL(config.url, config.baseURL);
    // parse pathName to implement variables
    Object.entries(config.urlParams || {}).forEach(([
        k,
        v,
    ]) => {
        currentUrl.pathname = currentUrl.pathname.replace(`:${k}`, encodeURIComponent(v));
    });

    const authPart = currentUrl.username && currentUrl.password ? `${currentUrl.username}:${currentUrl.password}` : '';
    return {
        ...config,
        baseURL: `${currentUrl.protocol}//${authPart}${currentUrl.host}`,
        url: currentUrl.pathname,
    };
});


// use like : 
instanceAxios.get('/issues/:uuid', {
   urlParams : {
       uuid: '123456789
   }
})

對於打字稿用戶,您需要將其添加到您的 .d.ts 文件之一中

declare module 'axios' {
    interface AxiosRequestConfig {
        urlParams?: Record<string, string>;
    }
}

(這是一個 POC,沒有經過真正的測試,如果您發現有問題,請不要猶豫)

你可以這樣做:

    getProduct = (id) => axios.get(`product/${id}`);

我總是這樣做:

const res = await axios.get('https://localhost:3000/get', { params: { myParam: 123 } });

我發現這比模板字符串更清晰。

更多解釋在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM