在 javascript 函数中将 fetch 转换为 axios

Covert fetch to axios in a javascript function

我需要一些帮助来用 axios 替换 fetch

export const fetchSecret = async (secretName) => {
    const token = await getFunctionAppToken();
    const headers = {
        Authorization: `Bearer ${token}`,
    };
    const url = `${blbl.GetSecretFromVault}?secretName=${secretName}`;

    return Promise.all([fetch(url, { method: "get", headers })])
        .then(([response]) => {
            const res = response.text();
            return res;
        })
        .catch((error) => {
            return Promise.reject(error);
        });
};

我卡在了 const res = response.text() for axios 的那一行。

return Promise.all([axios.get(url, { headers })])
            .then(([response]) => {
                const res = ??????????
                return res;

axios自动解析响应体流为data,见response schema.

您还可以通过 responseType 选项通知 Axios 期待文本响应。

最后,我总是喜欢使用 params 选项来传递查询参数,因为它确保正确 URL-encoding。

export const fetchSecret = async (secretName) =>
  (await axios.get(blbl.GetSecretFromVault, {
    headers: {
      Authorization: `Bearer ${await getFunctionAppToken()}`
    },
    params: { secretName },
    responseType: "text"
  })).data

我不知道你为什么要使用 Promise.all() 所以省略了它。

您的 .catch() 也是多余的,因此也不包含在内。


(await axios.get(...)).data 只是

的一个较短版本
const response = await axios.get(...)
return response.data

或没有await...

return axios.get(...).then(response => response.data)