英文:
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()
传递头信息,但服务器不允许。
英文:
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(
'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';
}
}
Function that uses Axios:
// function that uses 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);
})
}
And here is my error. I've tried to pass headers to axios.get()
already, but the server didn't allow them.
答案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.
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.
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'],
// });
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论