如何将Fetch转换为Axios?转换后出现401错误
解决Axios调用ExchangeRates API时的401认证错误
你提供的Fetch代码是通过请求头传递apikey完成认证的,而你朋友的Axios代码存在URL格式错误,这大概率是你仍出现401的核心原因。
正确的Axios写法有两种:
方式一:和Fetch逻辑一致,用请求头传递apikey(推荐,符合API文档规范)
const API = "https://api.apilayer.com/exchangerates_data"; axios.get(`${API}/symbols`, { headers: { 'apikey': API_KEY // 键名严格匹配API要求,大小写不能错 } }) .then(response => { setCurrenciesData(response.data.symbols); setLoading(false); }) .catch(error => { console.error(error); setLoading(false); });
方式二:用URL参数传递apikey(修正朋友代码的格式错误)
你朋友的代码把URL参数的起始符写错了——第一个参数必须用?而非&,修正后代码如下:
const API = "https://api.apilayer.com/exchangerates_data"; axios.get(`${API}/symbols?apikey=${API_KEY}`) .then(response => { setCurrenciesData(response.data.symbols); setLoading(false); }) .catch(error => { console.error(error); setLoading(false); });
额外排查点:
- 确认
API_KEY变量拼写正确、未过期且拥有访问/symbols接口的权限 - 检查请求头的键名是否严格为
apikey(API明确要求,大小写错误会直接导致认证失败)
内容的提问来源于stack exchange,提问作者Rahil Ali
相关产品推荐
相关产品推荐

