为什么我可以用fetch而不是axios来获取api数据?

zbdgwd5y  于 2022-11-23  发布在  iOS
关注(0)|答案(1)|浏览(155)

我得到了这个测试代码:

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的正确方法是什么?

6tqwzwtp

6tqwzwtp1#

在Axios版本的https:///geolite中有三个斜杠。它应该是https://

相关问题