fetch API not sending data via post












2















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









share|improve this question

























  • Please show us the code that triggers submitedData method & also the code for state change before submitedData

    – Danyal Imran
    Jan 19 at 18:29











  • is done, I edited.

    – Showtime
    Jan 19 at 18:39
















2















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









share|improve this question

























  • Please show us the code that triggers submitedData method & also the code for state change before submitedData

    – Danyal Imran
    Jan 19 at 18:29











  • is done, I edited.

    – Showtime
    Jan 19 at 18:39














2












2








2








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









share|improve this question
















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






javascript node.js reactjs express






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 19 at 18:50









nem035

25.1k53962




25.1k53962










asked Jan 19 at 18:23









ShowtimeShowtime

153




153













  • Please show us the code that triggers submitedData method & also the code for state change before submitedData

    – Danyal Imran
    Jan 19 at 18:29











  • is done, I edited.

    – Showtime
    Jan 19 at 18:39



















  • Please show us the code that triggers submitedData method & also the code for state change before submitedData

    – Danyal Imran
    Jan 19 at 18:29











  • is done, I edited.

    – Showtime
    Jan 19 at 18:39

















Please show us the code that triggers submitedData method & also the code for state change before submitedData

– Danyal Imran
Jan 19 at 18:29





Please show us the code that triggers submitedData method & also the code for state change before submitedData

– Danyal Imran
Jan 19 at 18:29













is done, I edited.

– Showtime
Jan 19 at 18:39





is done, I edited.

– Showtime
Jan 19 at 18:39












1 Answer
1






active

oldest

votes


















2














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





share|improve this answer





















  • 1





    Thanks! It's working.

    – Showtime
    Jan 19 at 18:49











Your Answer






StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});














draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54270081%2ffetch-api-not-sending-data-via-post%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes









2














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





share|improve this answer





















  • 1





    Thanks! It's working.

    – Showtime
    Jan 19 at 18:49
















2














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





share|improve this answer





















  • 1





    Thanks! It's working.

    – Showtime
    Jan 19 at 18:49














2












2








2







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





share|improve this answer















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






share|improve this answer














share|improve this answer



share|improve this answer








edited Jan 19 at 18:49

























answered Jan 19 at 18:43









nem035nem035

25.1k53962




25.1k53962








  • 1





    Thanks! It's working.

    – Showtime
    Jan 19 at 18:49














  • 1





    Thanks! It's working.

    – Showtime
    Jan 19 at 18:49








1




1





Thanks! It's working.

– Showtime
Jan 19 at 18:49





Thanks! It's working.

– Showtime
Jan 19 at 18:49


















draft saved

draft discarded




















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54270081%2ffetch-api-not-sending-data-via-post%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Liquibase includeAll doesn't find base path

How to use setInterval in EJS file?

Petrus Granier-Deferre