繁体   English   中英

javascript function 中的 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);
        });
};

我被困在 axios 的 const res = response.text() 行。

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

Axios 自动将响应体 stream 解析为data ,请参见响应模式

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

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

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

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

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

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

  try {

    const { data } = await axios(url, { method: 'get', headers })
    return data;
  }
  catch (error) {
    return error
  }
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM