使用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)

如果我切换到邮递员,则可以在相同的网址上正常工作。

As you can see in the picture..

如果我将获取功能从生命周期方法中删除,那么它将对用户进行身份验证,并在终端中获取用户详细信息。 知道为什么会这样吗? 每一次帮助都非常有价值,因为我很困在这里。 谢谢:)

解决方法

在用户提交表单时执行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>
   )
  }
}

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...