这里我有一个登录表单,是我在react js中创建的。我使用的API根据登录凭证是否匹配给出“成功登录”或“身份验证失败。无法登录”的响应。在登录表单中,我使用react钩子和axios.post将“name”和“password”发送到API。如何打印从API返回的响应?
下面是Login.js组件:
import React, { Component } from "react";
import { useState, useEffect } from "react";
import axios from "axios";
import { Button, TextField } from "@mui/material";
class Login extends Component {
constructor(props) {
super(props);
this.state = {
name: "",
password: "",
};
}
changeHandler = (e) => {
this.setState({ [e.target.name]: e.target.value });
};
submitHandler = (e) => {
e.preventDefault();
console.log(this.state);
axios
.post("http://localhost:8080/users/login", this.state)
.then((response) => {
console.log(response);
})
.catch((error) => {
console.log(error);
});
};
render() {
const { name, password } = this.state;
return (
<div>
<h1>Login Page</h1>
<form onSubmit={this.submitHandler}>
<TextField
name="name"
label="Enter Username"
color="secondary"
focused
size="small"
variant="outlined"
onChange={this.changeHandler}
id="name"
value={name}
type="text"
placeholder="Username"
className="form-control"
/>
<p />
<TextField
name="password"
label="Enter Password"
color="secondary"
focused
size="small"
variant="outlined"
onChange={this.changeHandler}
id="password"
value={password}
type="text"
placeholder="Password"
className="form-control"
/>
<p />
<Button type="submit" variant="contained">
Login
</Button>
</form>
</div>
);
}
}
export default Login;
下面是控制台显示的内容:
{name: 'Mike', password: 'password1234'}
{data: 'Authentication Failed. Unable to login', status: 200, statusText: '', headers: AxiosHeaders, config: {…}, …}
{name: 'Mike', password: 'Pass1234'}
{data: 'Successful Login', status: 200, statusText: '', headers: AxiosHeaders, config: {…}, …}
我可以使用另一个react钩子来获取数据吗?API使用POST方法,所以我不知道如何做。
1条答案
按热度按时间eit6fx6z1#
下面是一个使用钩子的登录页面的基本例子。2在登录函数中,你应该调用你想要的API,并使用setResponse在屏幕上显示响应