[英]Why I can get and api data with fetch and not with axios?
我得到了这个测试代码:
import axios from 'axios';
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json"},
withCredentials: true
};
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
}
const readWithFetch = (basicAuth) => {
return new Promise(res=>{
let headers = new Headers();
headers.set('Authorization', basicAuth);
fetch('https://geolite.info/geoip/v2.1/country/me?pretty', {
method: 'GET',
headers: headers,
}).then(response => res(response.json()));
})
}
const readData = async () => {
let user = '<my_api_user>';
let passwd = '<my_api_key>';
let basicAuth = 'Basic ' + Buffer.from(user + ":" + passwd).toString('base64');
let geoData;
//geoData = await readWithFetch(basicAuth);
geoData = await readWithAxios(basicAuth, user, passwd);
console.log(geoData);
}
readData();
我试图理解为什么 readWithFetch 工作正常而 axios 被拒绝连接。 这是一个简单的基本身份验证……没什么特别的。
我已经尝试了所有这些 readWithAxios 版本:
版本 1
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json"},
withCredentials: true
};
console.log('options', options);
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
}
版本 2
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
withCredentials: true
};
console.log('options', options);
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
}
版本 3
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
method: 'GET',
url: 'https:///geolite.info/geoip/v2.1/country/me?pretty',
auth: {
username: user,
password: passwd
},
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
withCredentials: true
};
版本 4
return axios(options);
}
const readWithAxios = async (basicAuth, user, passwd) => {
let options = {
method: 'GET',
url: 'https:///geolite.info/geoip/v2.1/country/me?pretty',
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
withCredentials: true
};
return axios(options);
}
readWithAxios 的正确写法是什么?
https:///geolite
在 Axios 版本中有一个三重斜线。 应该是https://
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.