我使用 Axios 访问第三方 API 时出现错误,但使用 fetch() 可以完成任务。

huangapple go评论54阅读模式
英文:

I get an error when I use Axios to access a third-party API, but fetch() does the job

问题

最近,我想使用Axios从第三方API获取数据。我遇到了CORS错误。所以我决定使用fetch()来代替。

以下是代码。使用fetch()的函数:

// 使用fetch的函数
export default async function () {
    let ipData = await fetch(
        'https://api.ipdata.co/?api-key=<key>'
    );
    let parsedIpData = await ipData.json();
    console.log(parsedIpData);
    if (parsedIpData && parsedIpData.languages) {
        parsedIpData.languages.forEach((lang) => {
            if (lang.code == 'en' || lang.code == 'ru') {
                console.log('lang.code - ' + lang.code);
                return lang.code;
            } else {
                console.log('fallback locale - en');
                return 'en';
            }
        })
    } else {
        console.log('no response. fallback locale - en');
        return 'en';
    }
}

使用Axios的函数:

// 使用Axios的函数
export default async function () {
    axios.get(
        'https://api.ipdata.co/?api-key=<key>'
    ).then((response) => {
        if (response && response.languages) {
            response.languages.forEach((lang) => {
                if (lang.code == 'en' || lang.code == 'ru') {
                    console.log('lang.code - ' + lang.code);
                    return lang.code;
                } else {
                    console.log('fallback locale - en');
                    return 'en';
                }
            })
        } else {
            console.log('no response. fallback locale - en');
            return 'en';
        }
    }).catch((error) => {
        console.log(error);
    })
}

这是我的错误。我已经尝试向axios.get()传递头信息,但服务器不允许。
我使用 Axios 访问第三方 API 时出现错误,但使用 fetch() 可以完成任务。

英文:

Recently, I wanted to get data from a third-party API using Axios. I've got a CORS error. So I decided to use fetch() instead.

Here is the code. Function that uses fetch():

// function that uses fetch()
export default async function () {
    let ipData = await fetch(
        &#39;https://api.ipdata.co/?api-key=&lt;key&gt;&#39;
    );
    let parsedIpData = await ipData.json();
    console.log(parsedIpData);
    if (parsedIpData &amp;&amp; parsedIpData.languages) {
        parsedIpData.languages.forEach((lang) =&gt; {
            if (lang.code == &#39;en&#39; || lang.code == &#39;ru&#39;) {
                console.log(&#39;lang.code - &#39; + lang.code);
                return lang.code;
            } else {
                console.log(&#39;fallback locale - en&#39;);
                return &#39;en&#39;;
            }
        })
    } else {
        console.log(&#39;no response. fallback locale - en&#39;);
        return &#39;en&#39;;
    }
}

Function that uses Axios:

// function that uses Axios
export default async function () {
    axios.get(
        &#39;https://api.ipdata.co/?api-key=&lt;key&gt;&#39;
    ).then((response) =&gt; {
        if (response &amp;&amp; response.languages) {
            response.languages.forEach((lang) =&gt; {
                if (lang.code == &#39;en&#39; || lang.code == &#39;ru&#39;) {
                    console.log(&#39;lang.code - &#39; + lang.code);
                    return lang.code;
                } else {
                    console.log(&#39;fallback locale - en&#39;);
                    return &#39;en&#39;;
                }
            })
        } else {
            console.log(&#39;no response. fallback locale - en&#39;);
            return &#39;en&#39;;
        }
    }).catch((error) =&gt; {
        console.log(error);
    })
}

And here is my error. I've tried to pass headers to axios.get() already, but the server didn't allow them.
我使用 Axios 访问第三方 API 时出现错误,但使用 fetch() 可以完成任务。

答案1

得分: 1

代码部分已被省略,以下是您要翻译的文本:

The answer is updated. Look at the end of it, please.

It turned out that Axios always sent requests with X-Requested-With header, but it wasn't allowed at the server. Look at the screenshot below to make sure.

我使用 Axios 访问第三方 API 时出现错误,但使用 fetch() 可以完成任务。

So I decided to assign null to X-Requested-With header. I'm not sure if this is the right thing to do, so, please, feel free to educate me on this, if you want. Here is how axios.get() looks now:

axios.get(
    'https://api.ipdata.co/?api-key=<key>', {
        headers: {
            'X-Requested-With': null
        }
    }
).then((response) => {
    if (response.data && response.data.languages) {
        console.log(response.data.languages);
        response.data.languages.forEach((lang) => {
            if (lang.code == 'en' || lang.code == 'ru') {
                console.log('lang.code - ' + lang.code);
                return lang.code;
            } else {
                console.log('fallback locale - en');
                return 'en';
            }
        })
    } else {
        console.log(response);
        console.log('no response. fallback locale - en');
        return 'en';
    }
}).catch((error) => {
    console.log(error);
})

And it worked! I'm so glad! Thank you, everyone, for leading me to this answer!

P.S.: This thread helped me to understand the reason Axios and other libraries include X-Requested-With into request headers.

UPDATE:

@Quentin, you were right! Axios default headers were set in resources/js/bootstrap.js. But I didn't create or modify this file.

/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios';
window.axios = axios;

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// import Pusher from 'pusher-js';
// window.Pusher = Pusher;

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: import.meta.env.VITE_PUSHER_APP_KEY,
//     cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? 'mt1',
//     wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
//     wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
//     wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
//     forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? 'https') === 'https',
//     enabledTransports: ['ws', 'wss'],
// });
英文:

The answer is updated. Look at the end of it, please.

It turned out that Axios always sent requests with X-Requested-With header, but it wasn't allowed at the server. Look at the screenshot below to make sure.

我使用 Axios 访问第三方 API 时出现错误,但使用 fetch() 可以完成任务。

So I decided to assign null to X-Requested-With header. I'm not sure if this is the right thing to do, so, please, feel free to educate me on this, if you want. Here is how axios.get() looks now:

axios.get(
    &#39;https://api.ipdata.co/?api-key=&lt;key&gt;&#39;, {
        headers: {
            &#39;X-Requested-With&#39;: null
        }
    }
).then((response) =&gt; {
    if (response.data &amp;&amp; response.data.languages) {
        console.log(response.data.languages);
        response.data.languages.forEach((lang) =&gt; {
            if (lang.code == &#39;en&#39; || lang.code == &#39;ru&#39;) {
                console.log(&#39;lang.code - &#39; + lang.code);
                return lang.code;
            } else {
                console.log(&#39;fallback locale - en&#39;);
                return &#39;en&#39;;
            }
        })
    } else {
        console.log(response);
        console.log(&#39;no response. fallback locale - en&#39;);
        return &#39;en&#39;;
    }
}).catch((error) =&gt; {
    console.log(error);
})

And it worked! I'm so glad! Thank you, everyone, for leading me to this answer!

P.S.: This thread helped me to understand the reason Axios and other libraries include X-Requested-With into request headers.

UPDATE:

@Quentin, you were right! Axios default headers were set in resources/js/bootstrap.js. But I didn't create or modify this file.

/**
 * We&#39;ll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the &quot;XSRF&quot; token cookie.
 */

import axios from &#39;axios&#39;;
window.axios = axios;

window.axios.defaults.headers.common[&#39;X-Requested-With&#39;] = &#39;XMLHttpRequest&#39;;

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from &#39;laravel-echo&#39;;

// import Pusher from &#39;pusher-js&#39;;
// window.Pusher = Pusher;

// window.Echo = new Echo({
//     broadcaster: &#39;pusher&#39;,
//     key: import.meta.env.VITE_PUSHER_APP_KEY,
//     cluster: import.meta.env.VITE_PUSHER_APP_CLUSTER ?? &#39;mt1&#39;,
//     wsHost: import.meta.env.VITE_PUSHER_HOST ? import.meta.env.VITE_PUSHER_HOST : `ws-${import.meta.env.VITE_PUSHER_APP_CLUSTER}.pusher.com`,
//     wsPort: import.meta.env.VITE_PUSHER_PORT ?? 80,
//     wssPort: import.meta.env.VITE_PUSHER_PORT ?? 443,
//     forceTLS: (import.meta.env.VITE_PUSHER_SCHEME ?? &#39;https&#39;) === &#39;https&#39;,
//     enabledTransports: [&#39;ws&#39;, &#39;wss&#39;],
// });

huangapple
  • 本文由 发表于 2023年2月7日 04:14:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/75366125.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定