在Reactjs中使用fetch处理ajax请求时出错。

问题描述 投票:0回答:1

我正试图在我的组件中为一个POST请求做一些错误处理。由于某些原因,下面的内容没有显示警报。有什么好办法吗?

到目前为止的代码。

import React, { Component } from 'react';

class Contact extends Component {
 constructor(props) {
    super(props);
    this.state = {
    message: '',
    email: '', 
    loading: false,
    successMessage: ''
    };
  }

handleSubmit(e) {
    e.preventDefault();
  /*global fetch */
    fetch('https://xxxxxxxxxx.execute-api.eu-west-2.amazonaws.com/xxx',{
        method: "POST",
        body: JSON.stringify(this.state),
        headers: {
          'Accept': 'application/json',
          'Content-Type': 'application/json',
        },
      }).then(
        (response) => (response.json())
       ).then((response)=>{

       if (response.status === 'success'){
        alert("Message Sent."); 
        this.resetForm();
      }else if(response.status === 'fail'){
        alert("Message failed to send.");
      }
     /*    
     if (response.ok) {
      this.setState({ successMessage: true});
     }
     */
    });
  }

  onEmailChange(event) {
    this.setState({email: event.target.value});
  }

  onMessageChange(event) {
    this.setState({message: event.target.value});
  }


  render() {
    return (
      <div className="container mt-5">
      <h3>Contact</h3>
      <form id="contact-form" onSubmit={this.handleSubmit.bind(this)} method="POST">
    <div className="form-group mt-4">
        <label htmlFor="exampleInputEmail1">Email address</label>
        <input type="email" className="form-control" required aria-describedby="emailHelp" value={this.state.email} onChange={this.onEmailChange.bind(this)} />
    </div>
    <div className="form-group">
        <label htmlFor="message">Message</label>
        <textarea className="form-control" rows="5" required value={this.state.message} onChange={this.onMessageChange.bind(this)} />
    </div>
    <button type="submit" className="btn btn-primary">Submit</button>
    { this.state.successMessage &&
      <div className="alert alert-success mt-5" role="alert">
  Your message has been successfully sent. Thanks for your message!
</div> }
    </form>
      </div>
    );
  }
}
export default Contact;
javascript ajax reactjs
1个回答
0
投票
if (response.status === 200){
        alert("Message Sent."); 
        this.resetForm();
      }else
        alert("Message failed to send.");
      }

fetch成功时返回200,而不是 success


0
投票

你可以很容易地做到像这样,用一点折射,用 async/awaittry/catch 块。

async handleSubmit() {
  e.preventDefault();
  try {
    const response = await fetch(
      "https://xxxxxxxxxx.execute-api.eu-west-2.amazonaws.com/xxx",
      {
        method: "POST",
        body: JSON.stringify(this.state),
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      }
    );

    if (response.status === 200) {
      const jsonResponse = await response.json();
      alert("Message Sent");
      this.resetForm();
      this.setState({ successMessage: true });
    }

    alert("Message failed to send.");

  } catch (error) {
    console.log(error);
  }
}


0
投票

这个代码有问题。

 if (response.status === 'success'){
    alert("Message Sent."); 
    this.resetForm();
  }else if(response.status === 'fail'){
    alert("Message failed to send.");
  }

Response.status 返回上述状态代码之一。此处. 你应该检查其中一个状态整数代码,而不是成功失败。

或者你可以检查 返回一个布尔值。 返回一个布尔值。

所以你的代码会像

   if (response.ok){
    alert("Message Sent."); 
    this.resetForm();
  } else {
    alert("Message failed to send.");
  }

注意: 检查 在生产中使用之前,请先获取API浏览器支持。MDN

© www.soinside.com 2019 - 2024. All rights reserved.