【问题标题】:Why am I getting a network error on page refresh? (get request)为什么我在页面刷新时收到网络错误? (获取请求)
【发布时间】:2021-12-18 15:49:03
【问题描述】:

我在 useEffect() 中向 API 发出 get 请求。当我从主页导航到该页面时,它加载正常,但是一旦我刷新页面http://localhost:3000/coins/coin,我就会得到一个Unhandled Runtime Error: Error: Network Error

export async function getServerSideProps({ query }) {
  const id = query;
  return {
    props: { data: id },
  };
}

function index({ data }) {
  const coinURL = data.id; // bitcoin
  const apiEndpoint = `https://api.coingecko.com/api/v3/coins/${coinURL}`;
  const [currentUser, setCurrentUser] = useState();
  const [coinData, setCoinData] = useState([]);

  useEffect(() => {
    const getData = async () => {
      const res = await axios.get(apiEndpoint);
      const { data } = res;
      setCoinData(data);
    };
    const getCurrentUser = async () => {
      const res = await axios.get(
        `http://localhost:5000/api/users/${session?.id}`
      );
      const { data } = res;
      setCurrentUser(data);
    };
    getData();
    getCurrentUser();

  }, [coinData, currentUser]);
}

为什么会这样?

【问题讨论】:

  • 请分享更多代码sn-p,以便我们解答。可能您的apiEndpoint 来自道具。
  • 我正在使用 getServerSideProps 来获取 url 参数。然后将该 id 传递给 main 函数的 props。 const apiEndpoint = https://api.coingecko.com/api/v3/coins/${coinURL}

标签: javascript reactjs api axios next.js


【解决方案1】:

我建议这样做:

const getData = async () => {
    try {
        const res = await axios.get(apiEndpoint);
        const { data } = res;
        setCoinData(data);
    } catch(err) {
        console.log(err)
    }
};

const getCurrentUser = async () => {
    try {
        const res = await axios.get(
            `http://localhost:5000/api/users/${session?.id}`
        );
        const { data } = res;
        setCurrentUser(data);
    } catch(err) {
        console.log(err)
    }
};

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

如果这样做,您将能够查看确切的错误并进行修复。

【讨论】:

  • 这似乎本身就解决了问题。我有点困惑为什么......那是因为我在调用它们之前定义了 useEffect 之外的函数吗?还是仅仅因为添加了try catch?
  • 实际上现在它的日志记录错误在无限循环中中止请求导致 Firefox 无响应
猜你喜欢
  • 1970-01-01
  • 2018-12-31
  • 1970-01-01
  • 2019-04-30
  • 2021-07-29
  • 2012-10-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多