javascript React App URL和Backend URL在使用axios获取数据时被连接起来[关闭]

nukf8bse  于 2023-04-28  发布在  Java
关注(0)|答案(3)|浏览(110)

**关闭。**这个问题是not reproducible or was caused by typos。目前不接受答复。

此问题是由打印错误或无法再重现的问题引起的。虽然类似的问题可能是on-topic在这里,这一个是解决的方式不太可能帮助未来的读者。
昨天关门了。
Improve this question
在我的全栈应用中,我得到了app文件夹,里面还有一个serverclient文件夹。
当转到X URL时,触发了useEffect,它应该从localhost:4000/pets/cats中获取数据,但是我得到了一个错误:
http://localhost:3000/localhost:4000/pets/cats 404(Not Found)
由于某种原因,它正在尝试查找此URL:http://localhost:3000/localhost:4000/pets/cats(实际上不存在)。怎么修?

Here's the get method

The reducer
The useEffect where I should be getting the info

p4tfgftt

p4tfgftt1#

你需要为axios设置一个正确的基URL:
使用完整URL的示例:

useEffect(() => {
  (async () => {
    try {
      const url = "http://localhost:4000/pets/cats"; // Full URL
      await axios.get(url);
    } catch (err) {
      console.log("Some error: ", err);
    }
  })();
}, []);

使用基本URL的示例:

useEffect(() => {
  (async () => {
    try {
      const url = "/pets/cats";
      await axios.get(url, {
        baseURL: "http://localhost:4000", // Base URL
      });
    } catch (err) {
      console.log("Some error: ", err);
    }
  })();
}, []);
eqoofvh9

eqoofvh92#

你尝试调用API两次,所以api找不到,或者404,试试这个localhost:4000/pets/cats

mspsb9vt

mspsb9vt3#

axios认为你的url不是'domain',因为你忘记了http和localhost中间的双//,所以axios不识别它,并采用默认的服务器url,在这种情况下,你的localhost上运行,然后添加你的url作为补充。
https://stackabuse.com/handling-errors-with-axios/

相关问题