typescript 从API调用检索数据

2izufjch  于 2022-11-26  发布在  TypeScript
关注(0)|答案(1)|浏览(133)

我已经成功地从登录API调用中检索了数据,并返回了data变量,该变量记录了用户信息,如id、令牌、电子邮件,并成功地将其打印到控制台。

async function login(email: string, password: string, rememberMe: boolean) {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password, rememberMe }),
  };

  await fetch(`${API_URL}/auth/login`, requestOptions).then((response) => {
    if (response.ok === true) {
      response.json().then((data) => {
        console.log(data);
        if (data.success === true) {
          localStorage.setItem("USER_ID", data.id);
          localStorage.setItem("EMAIL", data.email);
          localStorage.setItem("ACCESS_TOKEN_KEY", data.token);
          return data;
        } else {
          return Promise.reject(new Error("toast.user.general_error"));
        }
      });
    } else {
      return Promise.reject(new Error(response.statusText));
    }
  });
}

但是,当登录到控制台时,我得到user = undefined,表明我的数据变量未定义

function login(email: string, password: string, rememberMe: boolean) {
  return (dispatch: ThunkDispatch<{}, void, AnyAction>) => {

    authService.login(email, password, rememberMe).then(
      (user) => {
        history.push("/student/dashboard");
        console.log("user = ", user);
      },
      (error) => {
        dispatch(failure(error.toString()));
      }
    );
  };
}

为什么我没有从我的fetch请求中检索用户变量?2我应该在返回data变量之前用一个promise来 Package 它吗?

esbemjvw

esbemjvw1#

Login必须返回顶层的内容,而不是then块中的内容。

async function login(email: string, password: string, rememberMe: boolean) {
  const requestOptions = {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ email, password, rememberMe }),
  };

  const response = await fetch(`${API_URL}/auth/login`, requestOptions);
  
  if (!response.ok) return new Error(response.statusText);

  const data = await response.json();
  console.log(data);
  if (data.success !== true) return new Error("toast.user.general_error");
  return data;
}

相关问题