【问题标题】:Covert fetch to axios in a javascript function在javascript函数中将fetch转换为axios
【发布时间】:2022-01-31 14:50:21
【问题描述】:

我需要一些帮助来在这里用 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 自动将响应体流解析为data,见response schema。你只想要return response.data。你为什么使用Promise.all()?为什么要从 Fetch 切换到 Axios?
  • @Phil 从 fetch 切换到 axios 是一个不同的对话,因为在开玩笑中模拟 fetch 时遇到了一些挑战(一个完全不同的对话)。我不想在这里更改代码的实现以避免破坏性更改。在这里,我认为 res 是一个用字符串解析的承诺。我想要与 axios 类似的东西。 data 不是 Promise 而是 json 对象。
  • 仅供参考,有很多方法可以mock fetch

标签: javascript axios fetch-api


【解决方案1】:

Axios 自动将响应体流解析为data,参见response schema

您还可以通过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() 也是多余的,因此也不包含在内。


(await axios.get(...)).data 只是一个较短的版本

const response = await axios.get(...)
return response.data

或者没有await...

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

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 2020-01-12
    • 1970-01-01
    • 2016-09-02
    • 2021-08-17
    • 2018-03-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多