0

I'm trying to make a POST request with my React form component to send my State object as the body, but i'm receiving the body as {}.

My form Component passes the state info to another React Component i made (a bootstrap Input) as prop.

I'm maintaining the info in the Parent's state (where i also do the POST) so this shouldn't be a problem..

My Form Component:

class AgregarReservaForm extends Component {

    constructor(props) {
      super(props);
      this.state = {
        titulo: ''
      }

      this.handleTitulo = this.handleTitulo.bind(this);
    }

    handleTitulo(event) {
      this.setState({titulo: event.target.value})
    }

    async handleSubmit(event) {
      event.preventDefault();
      let self = this;
      let response = await fetch('http://localhost:3001/reserva', {
        method: 'POST',
        body: JSON.stringify(self.state),
        headers: {
          'Content-Type': 'application/json; charset=utf-8'
        },
        mode: 'no-cors'
      });

      if(!response.ok) {
        throw new Error();
      }

    }

    render() {

      return (
        <form onSubmit={this.handleSubmit}>

          <InputText
            name="titulo" 
            value={this.state.titulo}
            onChange={this.handleTitulo}
          />
</form>

My Express POST Route:

app.post('/reserva', (req, res) => {
    let body = req.body;
    console.log(body);

    let nuevaReserva = new Reserva({
        titulo: body.titulo
    });

    nuevaReserva.save((err, reservaDB) => {
        if (err) {
            return res.status(500).json({
                ok: false,
                err
            });
        }

        res.json({
            ok: true,
            reservaDB
        });
    });
});

Consoloe.log(body) is printing '{}'.

Alejo Emanuel
  • 27
  • 1
  • 4
  • Did it print your state in handleSubmit..? Also can you check network tab in developer tool what data isgetting passed to your API. – Sukrut Bam Oct 17 '19 at 04:59
  • yes, it prints find in handleSubmit, and i'm seeing the same object being passed as the Request payload to my API :( – Alejo Emanuel Oct 17 '19 at 05:10
  • You need the `express.json()` middleware. http://expressjs.com/en/4x/api.html#req.body – Oluwafemi Sule Oct 17 '19 at 05:15
  • Have you used body-parser middleware? https://www.npmjs.com/package/body-parser – Srinivas Oct 17 '19 at 05:16
  • Don’t use 'no-cors' mode. Because you’re sending the request using 'no-cors' mode, the `Content-Type: application/json; charset=utf-8` request header you’re trying to add in your frontend JavaScript code isn’t actually getting added to the request. That’s one of the things you’re explicitly opting in to when you use 'no-cors' mode. So when the `http://localhost:3001/reserva` server receives the POST request, it doesn’t receive it with the correct MIME type. The server doesn’t know what the MIME type is for the POST body it gets, so it doesn’t know how to process it. – sideshowbarker Oct 17 '19 at 05:28
  • i'm using body-parser. Maybe it is the 'no-cors', but if i switch it to 'cors' i'll get the 'CORS policy access-control-allow-origin' and i couldn't fix that. – Alejo Emanuel Oct 17 '19 at 05:34
  • Yeah, the question stated here is an XY problem https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem. The real problem you need to solve is the *“CORS policy access-control-allow-origin”* problem — which you thought you could solve by using 'no-cors' mode. But that’s not the solution, so you need to (re)ask instead about how to fix the actual problem — the *“CORS policy access-control-allow-origin”* problem. And the short answer to that is, you need to CORS-enable `http://localhost:3001/reserva` server. Which for node/express you can do using the npm cors package. – sideshowbarker Oct 17 '19 at 06:24

1 Answers1

0

You would need to bind your handleSubmit method in order to access the correct this and subsequently state inside it

constructor(props) {
  super(props);
  this.state = {
    titulo: ''
  }

  this.handleTitulo = this.handleTitulo.bind(this);
  this.handleSubmit = this.handleSubmit.bind(this);
}
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400