NODEJS - AXIOS:错误: "url" 参数必须是字符串类型。收到 Url.parse 的对象类型。

12

我正在尝试使用AXIOS从rest API获取数据,如下所示:

require('dotenv').config();
const axios = require('axios');

var url = 'https://931eb067-05c0-492a-8129-48ebfc27d426-bluemix.cloudant.com/dummy/_design/NEW_VIEW_DESIGN/_view/new-view?include_docs=true';
axios.get({url,auth: {
    username: process.env.account,
    password: process.env.password 
}}).then((res)=>{console.log(res.data);})
.catch((e)=>{console.log(e)});

通过提供凭据,我可以单独访问所提到的URL,但是在使用AXIOS时出现以下错误:

"url"参数必须是字符串类型。在Url.parse中接收到对象类型

出了什么问题?

2个回答

14
axios.get({url,auth: {
    username: process.env.account,
    password: process.env.password
}}).then((res)=>{console.log(res.data);})

应该是这样的

axios.get(url, { auth: {
    username: process.env.account,
    password: process.env.password
}}).then((res)=>{console.log(res.data);})

1
括号必须在名称“auth”之前,但您将其放在之后。 - Amr Saber
正如Amr Saber所指出的,这个答案包含无效的JavaScript代码,正确的答案在此处 - GGAlanSmithee

9
您在配置文件参数中放置了url,但它必须放在配置之前。
axios.get(url, {auth: {
    username: process.env.account,
    password: process.env.password
}}).then((res)=>{console.log(res.data);})
.catch((e)=>{console.log(e)});

由于几乎所有的网站都使用 https,无论您是否需要进行身份验证,为什么以下代码会与作者遇到相同的错误而失败呢?const url = "https://www.cia.gov/the-world-factbook/countries/"; const response = await axios.get(url); const $ = cheerio.load(response.data);该网站不需要登录,我正在使用 async/await - Mike S.
@MikeS。如果您想要认真地帮助,您需要提出一个新的问题/疑问,并附上完整的示例和定义。使用您的代码,我得到了“ReferenceError: cheerio未定义”的错误。 - Timo
这个问题早已过去,不再相关。 - Mike S.

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接