You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中调用API发起fetch请求时出现多种错误

问题描述

我尝试从API https://transfermarkt-api.vercel.app/players/122153/transfers 获取数据,浏览器直接访问该URL能正常显示JSON数据,但运行fetch代码时出现错误。

运行的代码

fetch('https://transfermarkt-api.vercel.app/players/122153/transfers', {
  method: 'GET',
  headers: {
    'accept': 'application/json'
  }
})
.then(response => response.json())
.then(data => {
  console.log(data); // Handle the response data here
})
.catch(error => {
  console.error('Error:', error); // Handle errors here
});

控制台错误

控制台错误信息

解决方案

这个错误是**跨域资源共享(CORS)**限制导致的——浏览器出于安全策略,会阻止前端页面从不同域名的服务器请求数据,除非目标服务器明确允许你的域名访问。

解决方法有几种:

  • 使用后端代理:在自己的后端服务中发起请求,前端再请求自己的后端。比如用Node.js+Express写个简单代理:
// Node.js + Express 示例
const express = require('express');
const fetch = require('node-fetch');
const app = express();

app.get('/api/transfers', async (req, res) => {
  try {
    const response = await fetch('https://transfermarkt-api.vercel.app/players/122153/transfers');
    const data = await response.json();
    res.json(data);
  } catch (err) {
    res.status(500).json({ error: err.message });
  }
});

app.listen(3000, () => console.log('代理服务运行在3000端口'));

前端只需请求 http://localhost:3000/api/transfers 即可。

  • 开发环境临时绕过CORS:使用Chrome的「Allow CORS: Access-Control-Allow-Origin」这类插件,开启后可在开发测试时临时解决跨域问题,但不能用于生产环境。
  • 检查API是否支持JSONP:不过该API返回纯JSON格式,看起来不支持JSONP,此方法不适用。

内容的提问来源于stack exchange,提问作者Husky7110

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 17:23:11