这次获取可能出了什么问题?

what could be going wrong in this fetch?

我试过 solution 使用异步等待从多个 API 获取数据,但输出未定义,可能出了什么问题?

const getData = async (jwt) => {
  try {
    const [response1, response2, response3] = await Promise.all(
      [
        fetch("http://localhost:3000/api/confirmed"),
        fetch("http://localhost:3000/api/deaths"),
        fetch("http://localhost:3000/api/recovered"),
      ],
      {
        method: "GET",
        headers: {
          "user-agent": "vscode-restclient",
          "content-type": "application/json",
          accept: "application/json",
          authorization:
            "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkxlYW5uZSBHcmFoYW0iLCJ1c2VybmFtZSI6IkJyZXQiLCJpYXQiOjE1OTY1MDY4OTN9.KDSlP9ALDLvyy0Jfz52x8NePUejWOV_mZS6cq4-JZXs",
        },
      }
    );
    const { data1 } = await response1.json();
    const { data2 } = await response2.json();
    const { data3 } = await response3.json();
    console.log(data1, data2, data3);
  } catch (err) {
    console.error(`Error: ${err}`);
  }
};

getData();

Promise.all 只接受一个参数,一个 promises 数组。因此,您的第二个参数(带有 methodheaders 的对象)将被忽略。该对象需要作为第二个参数传递给 fetch 函数,而不是 Promise.all.

尝试以下操作:

const getData = async (jwt) => {
  try {
    const fetchOptions = {
      method: "GET",
      headers: {
        "user-agent": "vscode-restclient",
        "content-type": "application/json",
        accept: "application/json",
        authorization:
          "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MSwibmFtZSI6IkxlYW5uZSBHcmFoYW0iLCJ1c2VybmFtZSI6IkJyZXQiLCJpYXQiOjE1OTY1MDY4OTN9.KDSlP9ALDLvyy0Jfz52x8NePUejWOV_mZS6cq4-JZXs",
      },
    };
    const [response1, response2, response3] = await Promise.all(
      [
        fetch("http://localhost:3000/api/confirmed", fetchOptions),
        fetch("http://localhost:3000/api/deaths", fetchOptions),
        fetch("http://localhost:3000/api/recovered", fetchOptions),
      ],
    );
    const { data1 } = await response1.json();
    const { data2 } = await response2.json();
    const { data3 } = await response3.json();
    console.log(data1, data2, data3);
  } catch (err) {
    console.error(`Error: ${err}`);
  }
};

getData();