axios“ url”参数必须为字符串类型。收到类型未定义的错误

时间:2019-06-28 10:19:33

标签: javascript node.js electron axios

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

并打印字符串。 我希望你能帮帮我, 预先感谢。

2 个答案:

答案 0 :(得分:2)

您正在使用解构:

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

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

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

您需要将其更改为url

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

docaxios的正确示例:

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

答案 1 :(得分:0)

对我都有用:

 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))