【问题标题】:axios The "url" argument must be of type string. Received type undefined erroraxios “url”参数必须是字符串类型。收到类型未定义的错误
【发布时间】:2019-11-10 07:23:16
【问题描述】:

我正在开发一个电子应用程序,它试图从 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))

它打印了字符串。 我希望你可以帮助我, 提前致谢。

【问题讨论】:

  • 问题在于“url”参数而不是“downloadUrl”参数..

标签: javascript node.js electron axios


【解决方案1】:

你正在使用解构:

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

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

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

你需要改成url:

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

axios 的正确示例来自doc

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

【讨论】:

  • 问题是,如果您的 url 字符串变量被命名为“url”,它可以直接传递而无需密钥对结构,但如果 url 链接变量被命名,否则您需要一个对密钥结构
【解决方案2】:

两者都适合我:

 url = 'localhost:4000/getsomething'

    axios({
                        method: 'get',
                        url,
                        auth: {
                            username: 'Blue',
                            password: 'PowerRanger'
                       }
           }).then(function(response){//do stuff
               }).catch(err => console.log(err))

但是在不同的情况下,url 变量不是命名为 url 而是不同的:

    customurl = 'localhost:4000/getsomething'
    axios({
                        method: 'get',
                        url: customurl,
                        auth: {
                            username: 'Blue',
                            password: 'PowerRanger'
                       }
           }).then(function(response){//do stuff
                }).catch(err => console.log(err))

【讨论】:

    猜你喜欢
    • 2019-11-27
    • 1970-01-01
    • 2020-07-21
    • 2022-08-15
    • 2019-05-13
    • 2020-09-21
    • 2019-12-14
    • 1970-01-01
    相关资源
    最近更新 更多