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

Vue.js调用OpenWeatherMap API遇Invalid API key错误求解决

解决Vue.js中调用OpenWeatherMap API的Invalid API key错误

你在Vue.js应用中调用OpenWeatherMap API时持续收到以下错误:

"Invalid API key. Please see https://openweathermap.org/faq#error401 for more info."

结合你的代码,问题主要出在两个地方,以下是具体解决方法:

问题1:API Key格式错误

你的请求URL中,appid参数被错误地包裹在大括号里,这会导致API无法识别正确的密钥。

错误写法:

appid={dace6a593d778f8773c2fd033a16a91a}

正确写法:

appid=dace6a593d778f8773c2fd033a16a91a

问题2:地理定位的异步逻辑错误

navigator.geolocation.getCurrentPosition是异步方法,你的fetch请求在它完成前就执行了,此时latitude.value和longitude.value还是空值,不仅会导致请求参数无效,也会间接引发API密钥相关的错误提示。

你需要把fetch调用放到getCurrentPosition的回调函数内部,确保拿到有效经纬度后再发起API请求。

修正后的完整代码

<template></template>

<script>
import { onMounted, ref } from "@vue/runtime-core";
export default {
  setup() {
    const weatherData = ref(null);
    const latitude = ref("");
    const longitude = ref("");

    onMounted(() => {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition((position) => {
          latitude.value = position.coords.latitude;
          longitude.value = position.coords.longitude;
          
          // 拿到经纬度后再发起API请求
          fetch(
            `https://api.openweathermap.org/data/2.5/weather?lat=${latitude.value}&lon=${longitude.value}&appid=dace6a593d778f8773c2fd033a16a91a`
          )
            .then((data) => data.json())
            .then((response) => {
              weatherData.value = response;
              console.log(response);
            })
            .catch((err) => console.log(err.message));
        });
      } else {
        alert("你的浏览器不支持地理定位");
        console.log("你的浏览器不支持地理定位");
      }
    });

    return { weatherData };
  },
};
</script>

<style></style>

额外建议

  • 建议将API Key存入环境变量(比如.env文件),避免硬编码在代码中,提升安全性。
  • 可以添加加载状态,在请求完成前给用户提示,优化体验。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 11:25:30