如何解决使用Fetch的发布请求无法在componentDidMount中使用
非常感谢您的帮助。我是Web开发人员和使用ReactJS的新手。 我正在尝试使用电子邮件和密码作为凭据来创建登录页面。问题是,如果我将提取函数放到ComponentDidMount中,则会收到404错误,但是如果我从生命周期方法中删除它,它将连接到服务器,并且我在终端中收到用户的详细信息-我尚不知道如何使它们出现在控制台或我的react应用中。如果您可以建议这样做的方法,将不胜感激。我正在尝试获取登录的当前用户详细信息。
这是我的构造方法:
export default class Login extends React.Component {
constructor(props){
super(props);
this.state = {
user:[],email:'',password:''
}
对于电子邮件和密码输入,我在表单上附加了handleChange函数: 这是表单输入的功能:
handleChange = (e) =>{
this.setState({
[e.target.name]: [e.target.value]});
}
这是表格:
<input
type= "email"
name="email"
placeholder="Email address"
value={this.state.email}
onChange={event => this.handleChange(event)}
required
/>
<input
type="password"
name="password"
placeholder="Password"
value={this.state.password}
onChange={event => this.handleChange(event)}
required
/>
async componentDidMount(){
const url = 'http://localhost:3000/login';
const options = { method: 'POST',headers: {
'Content-Type': 'application/json','Accept': '*/*'
},body: JSON.stringify({email:this.state.email,password:this.state.password})
};
const response = await fetch(url,options);
let data = response.json();
this.setState({user: data.results})
}
在此阶段,我的控制台中出现404错误:( POST http:// localhost:3000 / login 404(未找到),而在终端中则出现此错误:
data:: {}
user:: []
user.length:: 0
TypeError: Cannot read property 'password' of undefined
at authenticateUser (/Users/noir/Documents/Dana/work/SocialCats/backend/controllers/login.js:16:16)
at processticksAndRejections (internal/process/task_queues.js:97:5)
如果我将获取功能从生命周期方法中删除,那么它将对用户进行身份验证,并在终端中获取用户详细信息。 知道为什么会这样吗? 每一次帮助都非常有价值,因为我很困在这里。 谢谢:)
解决方法
在用户提交表单时执行API调用。
在componentDidMount
,用户尚未输入电子邮件和密码。因此,您的apiCall会引发错误。
class Login extends React.Component {
handleSubmit = (e) => {
e.preventDefault();
// do your API call here.
}
render() {
return (
<form onSubmit={handleSubmit}>
/** all the other input tags */
</form>
)
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。