简体   繁体   English

无法读取未定义 reactjs Jwt Auth 的属性“令牌”

[英]Cannot read property 'token' of undefined reactjs Jwt Auth

Cannot read property 'token' of undefined Screenshot Attached无法读取附加的未定义屏幕截图的属性“令牌”

// Auth Service.js
    const login = (username, password) => {
  return axios
    .post(API_URL + "signin", {
      username,
      password,
    })
    .then((response) => {
      if (response.data && response.data.data && response.data.data.token) {
        localStorage.setItem("user", JSON.stringify(response.data));
      }

      return response.data;

    })
    .catch((err) => {
      console.log("An error occured: ", err);
    });
};

im getting this error if the credentials are not correct, its working fine if the login details are correct, also i want to show if the email or password is wrong i want to get the API server response message and show the response message below login button.如果凭据不正确,我会收到此错误,如果登录详细信息正确,则工作正常,我还想显示 email 或密码是否错误我想获取 API 服务器响应消息并在登录按钮下方显示响应消息. someone pls help me有人请帮助我

// Auth.js
export const login = (username, password) => (dispatch) => {
  return AuthService.login(username, password).then(
    (data) => {
      dispatch({
        type: LOGIN_SUCCESS,
        payload: { user: data },
      });

      return Promise.resolve();
    },
    (error) => {
      const message =
        (error.response &&
          error.response.data &&
          error.response.data.message) ||
        error.message ||
        error.toString();

      dispatch({
        type: LOGIN_FAIL,
      });

      dispatch({
        type: SET_MESSAGE,
        payload: message,
      });

      return Promise.reject();
    }
  );
};
// Login.js
 const handleLogin = (e) => {
    e.preventDefault();

    setLoading(true);

    form.current.validateAll();

    if (checkBtn.current.context._errors.length === 0) {
      dispatch(login(username, password))
        .then(() => {
          props.history.push("/home");
          window.location.reload();
        })
        .catch(() => {
          setLoading(false);
        });
    } else {
      setLoading(false);
    }
  };

  if (isLoggedIn) {
    return <Redirect to="/home" />;
  }

You can handle error in catch block by chaining catch() after then()您可以通过在then() catch()来处理 catch 块中的错误

 const login = (username, password) => { return axios.post(API_URL + "signin", { username, password, }).then((response) => { if (response.data.data.token) { localStorage.setItem("user", JSON.stringify(response.data)); } return response.data; }).catch((err)=>{ console.log("An error occured: ", err); }); };

You can set a default user object in localStorage and then check if it is not null or undefined.您可以在localStorage中设置一个默认用户object,然后检查它是否不是null或未定义。

const login = (username, password) => {
  return axios
    .post(API_URL + "signin", {
      username,
      password,
    })
    .then((response) => {
      if (response.data.data.token) {
        localStorage.setItem("user", JSON.stringify(response.data));
      }

      return response.data;

    }).catch((err)=>{
        localStorage.setItem("user", JSON.stringify({user: {token: null}}));
    });
};

The reason you are getting that error because response.data.data property is undefined and it is happening when credentials are invalid.您收到该错误的原因是response.data.data属性未定义,并且在凭据无效时发生。 You should see what is server returning and based on that handle the response and show relevant message to the user.您应该看到服务器返回的内容并基于该处理响应并向用户显示相关消息。

What you can do is make your if condition more strict by adding a and condition to it.您可以做的是通过添加一个 and 条件来使您的 if 条件更加严格。 like, by doing so, user will only be set in localStorage when the token property is received from the server:就像这样,当从服务器接收到令牌属性时,用户只会在 localStorage 中设置:

if (response.data && response.data.data && response.data.data.token) {
    localStorage.setItem("user", JSON.stringify(response.data));
}

// handle the case where the response is not as expected.
if (response.data && !response.data.data) {
    // show error to the user and clear user info in localStorage.
    // localStorage.setItem("user", null);
    // return something
}

and also add a catch block to handle server errors.并添加一个 catch 块来处理服务器错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM