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