使用MusixMatch API发起fetch请求异常求助及学习资源推荐
问题描述
我正在学习API的使用方法与适用场景,尝试调用MusixMatch API获取艺术家数据时遇到了问题。我编写了默认GET类型的fetch请求代码,还搭建了CORS代理解决跨域问题,但出现JSON解析错误:Uncaught (in promise) SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON"。打印响应对象显示状态码为200,但响应体为空。
我的代码
useEffect(() => { fetch( `https://corsproxylyricallydemo.herokuapp.com/https://api.musixmatch.com/ws/1.1/artist.get?artist_id=118&apikey=${ApiKey}` ) .then((res) => console.log("res", res.json())) .then((data) => console.log("data", data)) .catch((err) => console.log(err)); }, []);
响应对象信息
Response {type: 'cors', url: 'https://corsproxylyricallydemo.herokuapp.com/https…st_id=118&apikey=${API-KEY}', redirected: false, status: 200, ok: true, …} body: (...), bodyUsed: false, headers: Headers {}, ok: true, redirected: false, status: 200, statusText: "OK", type: "cors", url:"https://corsproxylyricallydemo.herokuapp.com/https://api.musixmatch.com/ws/1.1/artist.get?artist_id=118&apikey=${API_KEY}", [[Prototype]] : Response
解决方法
- 更换稳定的CORS代理:你使用的Heroku代理大概率已经失效,返回了HTML错误页面(这就是JSON解析时出现
<!DOCTYPE的原因)。可以自己用Node.js搭一个简单代理,比如借助cors-anywhere包,或者换用其他可靠的公共代理。 - 修正fetch处理逻辑:
res.json()是异步操作,直接console.log("res", res.json())只会打印Promise对象,且第一次调用后响应体被消费,后续then无法获取数据。调整代码如下:useEffect(() => { fetch( `https://your-reliable-proxy.com/https://api.musixmatch.com/ws/1.1/artist.get?artist_id=118&apikey=${ApiKey}` ) .then((res) => { if (!res.ok) throw new Error('请求响应异常'); return res.json(); }) .then((data) => console.log("data", data)) .catch((err) => console.log(err)); }, []); - 添加指定请求头:部分API需要明确指定接受JSON格式,在fetch中加入请求头:
fetch(url, { headers: { 'Accept': 'application/json' } }) - 验证API密钥有效性:确认
${ApiKey}变量已正确注入有效密钥,无拼写错误或过期问题。
API相关概念学习资源推荐
- MDN Web Docs API基础:从HTTP请求响应模型、fetch API用法到REST规范,都是权威入门内容。
- RESTful API设计指南:学习API的核心设计原则,比如资源定位、HTTP方法的正确使用场景。
- Postman实操教程:通过工具掌握API测试的基本流程,包括请求构造、响应分析、参数调试。
- 第三方API文档解读技巧:重点练习如何快速理解API的认证方式、参数规则、错误码含义,这是使用任何第三方API的必备能力。
内容的提问来源于stack exchange,提问作者Lucid
相关产品推荐
相关产品推荐

