Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

fetch API not sending data via post

I am having trouble sending data via post using Fetch API, the server only receives an empty JSON. Can someone help me? Basically, I'm updating the data in state and sending to API.

submitedData = request.

submitedData = async (event) => {
   event.preventDefault();
   let data = {produto: this.state.produto, preco: this.state.preco};
   data = JSON.stringify(data);
   const result = await fetch('/api/add', {
       method: 'post',
       body: data
   });
   const body = await result.json();
   if(result.status == 200){
       //if all that's ok
   }else{
       console.log(body.message);
   }
}

changeInput = change the states.

changeInput = (event) => {
    const field = event.target.name;
    this.setState({ [field]: event.target.value });
}

render = triggers submitedData.

render(){
    return(
        <Grid>
            <Row>
                <Col sm={12}>
                    <Form horizontal onSubmit={this.submitedData} >
                        <FormGroup>
                            <Col sm={1}> <b> Produto: </b> </Col>
                            <Col sm={8}> 
                                <FormControl type="text" placeholder="Produto" value={this.state.produto} onChange={this.changeInput} name="produto" required/>
                            </Col>
                        </FormGroup>
                        <FormGroup>
                            <Col sm={1}> <b> Preço: </b> </Col>
                            <Col sm={8}> 
                                <FormControl type="number" placeholder="Preço" value={this.state.preco} onChange={this.changeInput} name="preco" required />
                            </Col>
                        </FormGroup>
                        <FormGroup>
                            <Col smOffset={1} sm={8}>
                                <Button type="submit" bsStyle="success"> Salvar </Button>
                            </Col>
                        </FormGroup>
                    </Form>
                </Col>
            </Row>
        </Grid>
    );
}

API

var express = require('express');
var Crud = require('./database/Crud');
var bodyParser = require('body-parser');
var app = express();

app.use(bodyParser.json());

app.post('/api/add', function(req, res){
  res.send(req.body);
  console.log(req.body); // {} json empty
});
like image 963
Showtime Avatar asked Feb 04 '26 12:02

Showtime


1 Answers

You need to stringify the request body and add the JSON content type header.

const result = await fetch('/api/add', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data)
});
like image 154
nem035 Avatar answered Feb 06 '26 02:02

nem035



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!