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

React中axios调用某API无返回但另一接口正常,如何解决?

React调用红酒API无返回的解决方法

可能原因及对应解决方案

  • 跨域拦截
    这是最常见的原因,公共API如果没有配置允许跨域的响应头,浏览器会基于同源策略直接拦截请求,你可以打开浏览器控制台的「网络」面板,看对应请求的状态,如果显示CORS错误就属于这类问题。
    解决方法:
    1. 本地开发阶段配置代理:如果是Vite项目,在vite.config.js中配置server.proxy指向https://api.sampleapis.com;如果是Create React App项目,在package.json中新增proxy字段值为该接口域名即可绕开本地跨域限制。
    2. 线上部署阶段:通过自己的后端服务转发该接口请求,避免前端直接调用跨域接口。
  • 接口本身不可用
    你可以直接在浏览器地址栏输入https://api.sampleapis.com/wines/reds测试,如果直接访问都无法返回JSON数据,说明该接口已经下线、服务故障或者有访问频次限制,直接更换其他同类型的公开数据接口即可。
  • 网络环境限制
    部分公司或者区域的网络防火墙可能会拦截未知域名的请求,可以切换手机热点等其他网络环境重试。

代码优化建议

你当前的代码混用了async/await和.then/.catch的写法,虽然不会影响功能,但可以统一写法逻辑更清晰,同时添加超时配置避免长时间无响应:

import React, { useState, useEffect } from "react";
import axios from "axios";
export default function App() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    getData()
  }, []);

  async function getData() {
    try {
      const response = await axios.get("https://api.sampleapis.com/wines/reds", {
        timeout: 10000 // 10秒超时
      })
      setData(response.data);
    } catch (err) {
      console.error("Error fetching data: ", err);
      setError(err);
    } finally {
      setLoading(false);
    }
  }

  if (loading) return "Loading...";
  if (error) return "Error!";
  return (
    <>
      <pre>{JSON.stringify(data, null, 2)}</pre>
    </>
  ); 
}

注意该接口返回的是数组结构,后续业务渲染时直接遍历即可,不需要和randomuser接口一样取results字段。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 13:27:03