javascript - 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))
它打印了字符串。我希望你能帮助我,在此先感谢。
解决方案
您正在使用解构:
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'
}
});
推荐阅读
- c# - C#如何将datagridview的当前行复制到单个数据行?
- json - 如何使用键和值输出正确的结果?
- react-native - 在现有的 react native 项目中使用 redux 以及它对项目的影响
- mysql - #1054 - 同一表 mysql 版本 5.6.4 的子查询中的“where 子句”中的未知列“ats2”
- haxe - 可以制作名为“Map”的自定义类,并且仍然引用 Haxe“Map”类吗?
- visual-studio-2017 - 如何防止 vc_redist.x##.exe (VS2017) 由于挂起的重新启动而出现模棱两可的失败?
- html - 输入类型号默认为 0,但如果它从 1 开始,则在提交时进行验证
- docker - docker-compose 运行现有容器
- asp.net-mvc - 在日期之间执行搜索时出现 ASP .NET MVC 错误
- c# - 在 MouseEnter 中使用 while 循环