3

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
});
0

1 Answer 1

3

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)
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.