Axios 响应未定义

Vas*_*per 2 javascript reactjs axios

在 axios post req 之后显示服务器身份验证响应时,我遇到了一些问题。我正在尝试控制台日志服务器响应错误消息:“请在表单提交后输入所有必填字段。控制台一直显示“未定义”。在服务器端一切都很好,网络选项卡显示正确的响应。

const Login = () => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [errors, setErrors] = useState("");

  const { getLoggedIn } = useContext(AuthContext);
  const history = useHistory();
  async function login(e) {
    e.preventDefault();
    try {
      const loginData = {
        email,
        password,
      };

      const res = await axios
        .post("http://localhost:5000/auth/login", loginData)
        .then((result) => {
          console.log(result.data);
        });

      await getLoggedIn();

      history.push("/player");
    } catch (err) {
      console.log(err.data);
    }
  }

  return (
    <div className="authWrapper">
      <form className="box" onSubmit={login}>
        <h1>LOGIN</h1>
        <input
          autoComplete="off"
          className="input"
          type="email"
          placeholder="Email"
          onChange={(e) => setEmail(e.target.value)}
          value={email}
        />
        <input
          autoComplete="off"
          className="input"
          type="password"
          placeholder="Password"
          onChange={(e) => setPassword(e.target.value)}
          value={password}
        />
        <button className="submit" type="submit">
          {`Log in${" "}`}
          <FontAwesomeIcon icon={faArrowRight}></FontAwesomeIcon>
        </button>

        <Link to="/register">
          <button className="changeForm">
            {`Register${" "}`}
            <FontAwesomeIcon icon={faSync}></FontAwesomeIcon>
          </button>
        </Link>
      </form>
    </div>
  );
};

export default Login;
<div></div>;
Run Code Online (Sandbox Code Playgroud)

控制台错误

网络登录端点响应

Sin*_*man 6

你们都在等待响应async/await并使用承诺链接线.post().then().catch()

尝试这个:

axios.post("http://localhost:5000/auth/login", loginData)
      .then((result) => {
          console.log(result.data);
          await getLoggedIn();
          history.push("/player");
        })
      .catch(err => {
         console.log(err)
      })
Run Code Online (Sandbox Code Playgroud)


Ikd*_*emm 5

只是为了在已经说过的内容上添加一些内容。如果您使用await ,则不需要使用.then()来实现promise 。你可以这样尝试:

const res = await axios.post("http://localhost:5000/auth/login", loginData)
console.log(res.data);
Run Code Online (Sandbox Code Playgroud)

您将等待服务器的响应。一旦获得它,它将存储在您创建的 res 常量中。另外,您需要在每次编写尝试后添加一个catch块。