在使用 Axios 发送 GET 请求并进行基本认证时,可能会遇到认证无效的问题。以下是一个包含代码示例的解决方法:
const axios = require('axios');
const username = 'your-username';
const password = 'your-password';
const url = 'https://example.com/api/data';
const config = {
auth: {
username: username,
password: password
}
};
axios.get(url, config)
.then(response => {
// 处理响应数据
console.log(response.data);
})
.catch(error => {
// 处理错误
console.error(error);
});
在上面的代码中,我们首先定义了基本认证所需的用户名和密码,然后创建了一个 config
对象,将用户名和密码作为 auth
属性的值传递给它。
接下来,我们使用 axios.get()
方法发送 GET 请求,并将 API 的 URL 和 config
对象作为参数传递给它。
最后,我们通过 then()
方法处理成功的响应,并通过 catch()
方法处理错误。
请确保将 your-username
和 your-password
替换为您自己的用户名和密码,https://example.com/api/data
替换为您要发送 GET 请求的实际 URL。
上一篇:Axios:请求暂停