相关疑难解决方法(0)

在React中处理Axios错误

我有一个React组件,它调用一个函数getAllPeople

componentDidMount() {
   getAllPeople().then(response => {
      this.setState(() => ({ people: response.data }));
    });
  } 
Run Code Online (Sandbox Code Playgroud)

getAllPeople在我的api模块中:

export function getAllPeople() {
  return axios
    .get("/api/getAllPeople")
    .then(response => {
      return response.data;
    })
    .catch(error => {
      return error;
    });
}
Run Code Online (Sandbox Code Playgroud)

我认为这是一个非常基本的问题,但是假设我要在根组件(在我的componentDidMount方法中)而不是在api函数中处理错误,该根组件如何知道我的axios调用是否返回错误?即,处理来自axios承诺的错误的最佳方法是什么?

error-handling reactjs axios

8
推荐指数
3
解决办法
2万
查看次数

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> …
Run Code Online (Sandbox Code Playgroud)

javascript reactjs axios

2
推荐指数
2
解决办法
2万
查看次数

标签 统计

axios ×2

reactjs ×2

error-handling ×1

javascript ×1