Axios:.then和.catch不能在Axios post函数中运行

5vf7fwbs  于 2023-10-18  发布在  iOS
关注(0)|答案(1)|浏览(149)

我已经多次阅读这段代码,但我找不到任何错误。尽管API发布成功,.then()和.catch()似乎没有运行。

const handleLogin = () => {
    axios
      .post(
        'http://localhost:3000/login',
        {
          email: emailLogin,
          password: passwordLogin,
        },
        {
          headers: {
            'Content-Type': 'application/json',
          },
          withCredentials: true,
        },
      )
      .then((response) => {
        localStorage.setItem('name', response.data.name)
        setCookies('access_token', response.data.accessToken, { path: '/' })
        if (emailLogin.includes('@admin-kd.com')) {
          return window.location.replace('http://localhost:5173/admin')
        } else {
          return window.location.replace('http://localhost:5173/')
        }
      })
  }

  <button onClick={handleLogin} type="button" value={'Login'} />

控制台日志之前的职位,它正确地这样做,但一旦我试图控制台日志内的.then()或.catch(),它根本没有

de90aj5v

de90aj5v1#

=>添加Catch块并检查控制台的错误信息:(同时请检查浏览器中的网络选项卡- API是否成功)
注意:当您需要等待API响应时,使用WARTEC和await是一个很好的实践。
样本代码:

1)代码使用Async和Await实现,使用catch块

const handleLogin = async () => {
  try {
    const response = await axios.post(
      "http://localhost:3000/login",
      {
        email: emailLogin,
        password: passwordLogin,
      },
      {
        headers: {
          "Content-Type": "application/json",
        },
        withCredentials: true,
      }
    );

    localStorage.setItem("name", response.data.name);
    setCookies("access_token", response.data.accessToken, { path: "/" });

    if (emailLogin.includes("@admin-kd.com")) {
      window.location.replace("http://localhost:5173/admin");
    } else {
      window.location.replace("http://localhost:5173/");
    }
  } catch (error) {
    console.error(error);
  }
};

2)如果您不想添加Async和Await

const handleLogin = () => {
  axios
    .post(
      "http://localhost:3000/login",
      {
        email: emailLogin,
        password: passwordLogin,
      },
      {
        headers: {
          "Content-Type": "application/json",
        },
        withCredentials: true,
      }
    )
    .then((res) => {
      localStorage.setItem("name", response.data.name);
      setCookies("access_token", response.data.accessToken, { path: "/" });

      if (emailLogin.includes("@admin-kd.com")) {
        return window.location.replace("http://localhost:5173/admin");
      } else {
        return window.location.replace("http://localhost:5173/");
      }
    })

    .catch((error) => {
      console.log(error);
    });
};

让我知道,如果你有疑问。

相关问题