使用Axios调用第三方API遇CORS错误,fetch()可正常工作求助
Axios调用第三方API遇CORS错误的解决方案求助
最近调用第三方API时,用Axios会触发CORS错误,但改用fetch()就能正常完成请求。以下是两种实现的代码,试过给Axios添加请求头但服务器不允许,附上错误截图,求解决办法。
使用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'; } }
使用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); }) }
错误截图

可能的解决方向
- 消除Axios与fetch的请求头差异:fetch默认不会发送
Content-Type: application/json这类头,而Axios默认会带,这可能触发浏览器的预检请求。可以尝试修改Axios的请求头:
axios.get('https://api.ipdata.co/?api-key=<key>', { headers: { 'Content-Type': 'text/plain' } })
或者直接清空Axios的默认公共请求头:
axios.defaults.headers.common = {};
- 检查
withCredentials配置:确保Axios没有开启凭证携带,因为fetch默认是不携带的,尝试显式设置:
axios.get('https://api.ipdata.co/?api-key=<key>', { withCredentials: false })
- 使用独立Axios实例测试:如果项目中有全局Axios拦截器或默认配置,可能添加了额外头导致CORS问题,创建新实例测试:
const axiosInstance = axios.create(); axiosInstance.get('https://api.ipdata.co/?api-key=<key>') .then(res => console.log(res)) .catch(err => console.log(err));
- 前端代理转发请求:如果以上方法都无效,可以通过本地代理转发请求,绕过浏览器的CORS限制。比如在Vue项目的
vue.config.js中配置:
module.exports = { devServer: { proxy: { '/ipdata': { target: 'https://api.ipdata.co', changeOrigin: true, pathRewrite: { '^/ipdata': '' } } } } }
之后请求改为axios.get('/ipdata/?api-key=<key>')
内容的提问来源于stack exchange,提问作者user18630923
相关产品推荐
相关产品推荐

