JavaScript调用yesno.wtf趣味API时触发CORS跨域报错问题
问题描述
有一款趣味API可针对任意提问返回YES、NO或MAYBE三种结果,官网地址为:https://yesno.wtf/
在本地HTML文件中通过JavaScript接入该API时触发报错,具体报错信息如下:
Access to fetch at 'https://yesno.wtf/assets/yes/2.gif' from origin 'http://127.0.0.1:5500' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
GET https://yesno.wtf/assets/yes/2.gif net::ERR_FAILED 404
Uncaught (in promise) TypeError: Failed to fetch at HTMLFormElement.decide (index.html:60:11)
问题根因
- 请求地址完全写错:代码里定义的
wtfUrl是静态GIF图片的存放路径,不是API的请求入口,这个路径下只有图片文件,不会返回代码里要解析的JSON数据,请求直接报404。 - 多余请求头触发跨域拦截:给图片请求加了
accept: application/json的自定义头,会触发浏览器的跨域预检机制,而静态图片路径没有配置跨域允许头,直接被浏览器拦截。 - 缺少错误处理逻辑:fetch请求没有加catch分支,请求失败时直接抛出未捕获的Promise异常,控制台飘红。
修复步骤
- 把请求地址换成正确的API入口
https://yesno.wtf/api,这个接口默认配了跨域允许头,本地开的静态页面直接请求不会被CORS拦截。 - 删掉没必要的自定义请求头,直接发默认GET请求就行。
- 增加请求状态判断和异常捕获,避免控制台抛出未捕获错误。
- 每次提交新问题前清空上一次的结果,不然多次提交会堆一堆图片在页面上。
修复后完整代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Ask.Net</title> <style> .d-flex { display: flex; } .justify-center { justify-content: center; } .flex-col { flex-direction: column; } .align-center { align-items: center; } .img-container{ margin-top: 2rem; } #img-article img{ max-width: 300px; border-radius: 8px; } button{ margin-top: 1rem; padding: 0.4rem 1rem; cursor: pointer; } </style> </head> <body> <form class="d-flex flex-col align-center"> <label for="task"> <h1>Welcome to Ask.Net</h1> </label> <input placeholder="Enter your questions here..." type="text" id="task" /> <button type="submit">获取答案</button> </form> <section class="img-container d-flex flex-col align-center"> <article id="img-article"></article> <h1 id="answer-text"></h1> </section> <script> const wtfUrl = "https://yesno.wtf/api"; const imgArticle = document.getElementById("img-article"); const ansText = document.getElementById("answer-text"); document.querySelector("form").addEventListener("submit", decide); async function decide(event) { event.preventDefault(); // 清空历史结果 imgArticle.innerHTML = ''; ansText.textContent = '正在获取答案...'; try { const response = await fetch(wtfUrl); if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`); const result = await response.json(); const img = document.createElement("img"); img.src = result.image; imgArticle.appendChild(img); ansText.textContent = result.answer.toUpperCase(); } catch (err) { ansText.textContent = '获取答案失败,请稍后重试'; console.error('请求错误:', err); } } </script> </body> </html>
修复后提交表单即可正常获取随机答案和对应动图,无跨域、404报错。
内容的提问来源于stack exchange,提问作者Mr Jerry Glass
相关产品推荐
相关产品推荐

