I got this test code:
JavaScript
x
41
41
1
import axios from 'axios';
2
3
const readWithAxios = async (basicAuth, user, passwd) => {
4
let options = {
5
auth: {
6
username: user,
7
password: passwd
8
},
9
headers: { "Content-Type": "application/json"},
10
withCredentials: true
11
};
12
13
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
14
}
15
16
const readWithFetch = (basicAuth) => {
17
return new Promise(res=>{
18
let headers = new Headers();
19
headers.set('Authorization', basicAuth);
20
21
fetch('https://geolite.info/geoip/v2.1/country/me?pretty', {
22
method: 'GET',
23
headers: headers,
24
}).then(response => res(response.json()));
25
})
26
}
27
28
const readData = async () => {
29
let user = '<my_api_user>';
30
let passwd = '<my_api_key>';
31
let basicAuth = 'Basic ' + Buffer.from(user + ":" + passwd).toString('base64');
32
33
let geoData;
34
35
//geoData = await readWithFetch(basicAuth);
36
geoData = await readWithAxios(basicAuth, user, passwd);
37
38
console.log(geoData);
39
}
40
readData();
41
I’m trying to understand why readWithFetch works fine and axios gets connection refused. It’s a simple basic auth… nothing fancy.
I’ve tried all these readWithAxios versions:
version 1
JavaScript
1
14
14
1
const readWithAxios = async (basicAuth, user, passwd) => {
2
let options = {
3
auth: {
4
username: user,
5
password: passwd
6
},
7
headers: { "Content-Type": "application/json"},
8
withCredentials: true
9
};
10
11
console.log('options', options);
12
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
13
}
14
version 2
JavaScript
1
14
14
1
const readWithAxios = async (basicAuth, user, passwd) => {
2
let options = {
3
auth: {
4
username: user,
5
password: passwd
6
},
7
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
8
withCredentials: true
9
};
10
11
console.log('options', options);
12
return axios.get('https:///geolite.info/geoip/v2.1/country/me?pretty', options);
13
}
14
version 3
JavaScript
1
12
12
1
const readWithAxios = async (basicAuth, user, passwd) => {
2
let options = {
3
method: 'GET',
4
url: 'https:///geolite.info/geoip/v2.1/country/me?pretty',
5
auth: {
6
username: user,
7
password: passwd
8
},
9
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
10
withCredentials: true
11
};
12
version 4
JavaScript
1
14
14
1
return axios(options);
2
}
3
4
const readWithAxios = async (basicAuth, user, passwd) => {
5
let options = {
6
method: 'GET',
7
url: 'https:///geolite.info/geoip/v2.1/country/me?pretty',
8
headers: { "Content-Type": "application/json", 'Authorization': basicAuth},
9
withCredentials: true
10
};
11
12
return axios(options);
13
}
14
What is the correct way to write readWithAxios ?
Advertisement
Answer
You have a triple slash in https:///geolite
in the Axios versions. It should be https://