Problema con la solicitud POST en React

Aug 16 2020

El clic del botón está funcionando, ya que puedo ver el registro, pero la solicitud POST no ocurre. He creado un cuadro de entrada simple, y cuando se hace clic en el botón, debería enviar una solicitud POST al servidor.

No puedo entender por qué la solicitud POST nunca se lleva a cabo, así que ayúdame a resolverlo.

Comment.js:

import React from 'react';

export class Comment extends React.Component {
    constructor(props){
        super(props);
        this.handleClick = this.handleClick.bind(this);
  
    }


    handleClick() {
        //SEND POST request
        console.log('handling click');
        const xhr = new XMLHttpRequest();
        const URL = "http://localhost:8080/api/comments"
        xhr.onreadystatechange = () => {
            if(xhr.readyState === XMLHttpRequest.DONE){
              console.log('POST request sent, comment posted.')
            }
        xhr.open('POST',URL);
        xhr.setRequestHeader('Content-type', 'text/plain');
        xhr.send(document.getElementById('comment-box').value);
        }

    }


    
    render(){
        const comment_form = (
           <div className="posts">
              <input type="text" id="comment-box" name="comment" placeholder="Say something nice." />
              <button className="submit-button" type="button" onClick={this.handleClick}> Comment </button>
           </div>
        );
        return comment_form;
    }
}

Respuestas

3 Asutosh Aug 16 2020 at 03:40

Tuviste un error de sintaxis como cerrar} de onReadyState eventhandler no estaba en el lugar correcto

import React from "react";
import "./styles.css";

export class Comment extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
  }

  handleClick() {
    //SEND POST request
    console.log("handling click");
    const xhr = new XMLHttpRequest();
    const URL = "http://localhost:8080/api/comments";
    xhr.onreadystatechange = () => {
      if (xhr.readyState === XMLHttpRequest.DONE) {
        console.log("POST request sent, comment posted.");
      }
    };
    xhr.open("POST", URL);
    xhr.setRequestHeader("Content-type", "text/plain");
    console.log(document.getElementById("comment-box").value);
    xhr.send(document.getElementById("comment-box").value);
  }

  render() {
    const comment_form = ( <
      div className = "posts" >
      <
      input type = "text"
      id = "comment-box"
      name = "comment"
      placeholder = "Say something nice." /
      >
      <
      button className = "submit-button"
      type = "button"
      onClick = {
        this.handleClick
      } >
      {
        " "
      }
      Comment {
        " "
      } <
      /button> <
      /div>
    );
    return comment_form;
  }
}

1 StarkJeon Aug 16 2020 at 03:32

Responder

La función de flecha se vincula thisy se llama a la devolución de llamada onreadystatechange cuando this === Comment. Entonces xhr.onreadystatechange no funciona.

 xhr.onreadystatechange = function() {
            if(xhr.readyState === XMLHttpRequest.DONE){
              console.log('POST request sent, comment posted.')
            }

Creo que la siguiente referencia es útil para usted. No es problema de reaccionar sino de función de flecha.
Esta referencia es escribir más claramente sobre ese problema.

Referencia

  1. Conversión de sintaxis antigua de Javascript a función de flecha