调用AccuWeather公开API遇GET请求401 Unauthorized错误求助
解决AccuWeather API 401未授权错误的方案
以下是针对你遇到的401错误的具体排查和解决步骤:
验证API密钥有效性
- 核对密钥拼写:直接登录AccuWeather开发者后台,复制粘贴正确的API密钥,避免手动输入时出现大小写错误、多余空格或字符遗漏。
- 检查密钥权限:确认你的密钥是否有权限访问
/locations/v1/cities/search接口,部分免费密钥可能仅开放特定功能接口。 - 查看密钥状态:检查密钥是否过期或被平台禁用,开发者后台会显示密钥的当前状态和调用限制。
修正请求URL
你当前使用的是相对路径/locations/v1/cities/search,如果没有配置本地代理指向AccuWeather的官方域名,这个请求会指向你的React项目本地服务器,导致401。应使用完整的API域名:const baseUrl = 'https://dataservice.accuweather.com'; const url = `${baseUrl}/locations/v1/cities/search?apikey=${apiKey}&q=${city}`;检查调用限制
AccuWeather免费版API有严格的调用频次限制(比如每日调用量上限),如果超出限制也会返回401。登录开发者后台查看你的调用统计,确认是否触发了限制。密钥安全优化(重要)
不要在前端代码中硬编码API密钥,容易被他人通过源码窃取。建议搭建后端代理服务,将API密钥存储在后端环境变量中,前端调用自己的后端接口,再由后端转发请求到AccuWeather API。
修改后的示例代码
import React from "react"; import { useState, useEffect } from 'react'; import './Citydata.css'; const Citydata = ({ cidade }) => { const [location, setLocation] = useState(null); const [error, setError] = useState(null); const apiKey = '你的有效API密钥'; // 替换为后台获取的正确密钥 const baseUrl = 'https://dataservice.accuweather.com'; useEffect(() => { const getLocation = (city) => { const url = `${baseUrl}/locations/v1/cities/search?apikey=${apiKey}&q=${city}`; fetch(url) .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); }) .then(data => { setLocation(data); setError(null); }) .catch(err => { console.error('获取位置信息失败:', err); setError('无法获取位置信息,请稍后重试。'); setLocation(null); }); }; if (cidade) { getLocation(cidade); } }, [cidade, apiKey]); // 基础渲染逻辑示例 return ( <div className="city-data"> {error && <p className="error">{error}</p>} {location && location.length > 0 && ( <div> <h3>{location[0].LocalizedName}</h3> <p>国家: {location[0].Country.LocalizedName}</p> </div> )} </div> ); } export default Citydata;
内容的提问来源于stack exchange,提问作者Gustavo Lacerda
相关产品推荐
相关产品推荐

