本文详解 fetch api 中发起 http 请求、处理响应及解析 json 的完整流程,涵盖常见错误(如 url 变量格式错误、promise 链误用)、api 密钥安全实践,并提供可直接运行的 html + javascript 示例。
本文详解 fetch api 中发起 http 请求、处理响应及解析 json 的完整流程,涵盖常见错误(如 url 变量格式错误、promise 链误用)、api 密钥安全实践,并提供可直接运行的 html + javascript 示例。
在前端开发中,使用 fetch() 获取远程 JSON 数据是基础但易出错的操作。你提供的代码存在两个关键问题:URL 中占位符未替换(如 {secret} 未替换成真实 API key),以及 .then() 调用位置错误导致 Promise 链断裂——console.log(fetch(...)) 会立即打印一个 Promise 对象,而非等待响应,后续 .then() 实际上附加到了 undefined 上,引发运行时错误。
以下是修正后的完整实现方案:
✅ 正确结构:异步请求 + 响应解析 + 错误处理
<!-- index.html -->
<meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Weather Data Fetch</title><label for="place">Enter a City Name (or use coordinates):</label>
<input type="text" id="place" placeholder="e.g., Seattle"><button id="get-data-button">Get Weather</button>
<div id="result"></div>
<script src="weather.js"></script>
// weather.js
const getDataButton = document.getElementById("get-data-button");
const resultDiv = document.getElementById("result");
getDataButton.addEventListener("click", async () => {
// ⚠️ 注意:此处仅为演示,实际项目中请将 API key 存于服务端或环境变量
const apiKey = "YOUR_API_KEY_HERE"; // 替换为从 https://openweathermap.org/api 申请的真实密钥
const lat = 47.6; // Seattle latitude
const lon = -122.3; // Seattle longitude
try {
const response = await fetch(
`https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${apiKey}&units=metric`
);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const data = await response.json();
console.log("✅ Parsed JSON:", data);
// 示例:显示城市名与温度
resultDiv.innerHTML = `
<h3>${data.name}, ${data.sys.country}</h3>
<p>Temperature: ${data.main.temp}°C</p><div class="aritcle_card flexRow artxards">
<div class="artcardd flexRow">
<a class="aritcle_card_img" rel="nofollow" href="/xiazai/skill4567" title="Comprehensive Three.js 3D graphics reference"><img
src="https://img.php.cn/upload/skill/000/000/081/179012895030480.jpg" alt="Comprehensive Three.js 3D graphics reference" onerror="this.onerror='';this.src='/static/lhimages/moren/morentu.png'" ></a>
<div class="aritcle_card_info flexColumn">
<a rel="nofollow" href="/xiazai/skill4567" title="Comprehensive Three.js 3D graphics reference" class="overflowclass">Comprehensive Three.js 3D graphics reference</a>
<p class="overflowclass">详细的 Three.js 3D 图形参考,涵盖场景设置、相机、几何体、材质、光照、动画、控制器、加载器、数学工具和调试。</p>
</div>
<a rel="nofollow" href="/xiazai/skill4567" title="Comprehensive Three.js 3D graphics reference" class="aritcle_card_btn flexRow flexcenter"><b></b><span>下载</span>
</a>
</div>
</div>
<p>Weather: ${data.weather[0].description}</p>
`;
} catch (err) {
console.error("❌ Fetch failed:", err);
resultDiv.innerHTML = `<p style="color:red;">Error: ${err.message}</p>`;
}
});
? 关键要点说明
- URL 拼接规范:使用模板字符串(`...${lat}...`)动态插入数值,切勿保留 {secret} 等占位符,否则请求会因无效 appid 被拒绝;
- Promise 链 vs async/await:原代码中 .then() 写在 console.log() 后属于语法错误;推荐使用 async/await 提升可读性与错误捕获能力;
- API 密钥安全:公开暴露 appid 可能导致配额盗用甚至计费风险。生产环境务必通过后端代理请求,或启用 OpenWeatherMap 的「Referer 白名单」限制;
- 响应验证:始终检查 response.ok 或 response.status,避免对失败响应(如 401/404)调用 .json() 导致解析异常;
- 参数建议:添加 &units=metric(或 imperial)使温度更符合本地习惯。
掌握这些实践,你就能稳定、安全、可维护地通过 fetch() 拉取并使用任意公开 JSON API 数据。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!










