首页 > 解决方案 > axios “url”参数必须是字符串类型。收到类型未定义的错误

问题描述

我正在开发一个电子应用程序,该应用程序试图从 unsplash API 下载照片并将其设置为墙纸。当我调用 API 时,我得到 200 OK 状态并获取下载 URL,但是当我尝试使用 axios 流方法下载照片时,我得到以下错误:

UnhandledPromiseRejectionWarning:TypeError [ERR_INVALID_ARG_TYPE]:“url”参数必须是字符串类型。接收类型未定义

这是功能代码:

ipcMain.on("getRandomWallpaper", async event => {
  const randomApi = `${apiGateway}/?client_id=${unsplashKey}`;
  const request = await axios({
    method: "get",
    url: randomApi
  });
  if (request.status === 200) {
    const downloadUrl = request.data.links.download;
    const imagePath = "./images";
    const download_image = async (downloadUrl, imagePath) => {
      await axios({
        downloadUrl,
        responseType: "stream"
      }).then(
        response =>
          new Promise((resolve, reject) => {
            response.data
              .pipe(fs.createWriteStream(imagePath))
              .on("finish", () => resolve())
              .on("error", e => reject(e));
          })
      );
    };
    download_image(downloadUrl, imagePath);
  } else {
    const status = request.status;
    console.error(`${status}: \n Something went wrong...`);
  }
});

当我尝试 console.log 函数内的 downloadUrl 参数时,它打印了一个值。我也做过

 console.log(typeoff(downloadUrl))

它打印了字符串。我希望你能帮助我,在此先感谢。

标签: javascriptnode.jselectronaxios

解决方案


您正在使用解构:

await axios({
    downloadUrl,
    responseType: "stream"
})

这意味着,您正在使用downloadUrl作为键,而不是url

await axios({
    downloadUrl: downloadUrl,
    responseType: "stream"
})

您需要将其更改为url

await axios({
    url: downloadUrl,
    responseType: "stream"
})

axios来自文档的适当示例:

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

推荐阅读