Having trouble sending information to the backend. Currently, I have the following fetch
function in my frontend:
function appending() {
console.log('in Appending');
console.log('formInfo', formInfo);
console.log('formInfofrom', formInfo.from)
fetch('http://localhost:3001/add-transaction', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: {
from: formInfo.from,
to: formInfo.to,
amount: formInfo.amount,
fee: formInfo.fee
}
}).then((backendResponse) => {
if(backendResponse.ok)
return backendResponse.json();
}).then((theJSON) => {
// ERROR: 1 - not enough funds
// ERROR: 0 - no errors
console.log('theJSON: ', theJSON);
console.log('Error is: ', theJSON.error);
if(theJSON.error === 1) {
console.log('Insufficient')
setBackendError("insufficient");
}
else if (theJSON.error === 0) {
console.log("Sufficient funds")
setBackendError("sufficient")
}
else {
console.log("Mongo error")
setBackendError("mongo");
}
}).catch((error) => {
console.log('error is', error);
})
}
formInfo
is a JSON object which has 4 key/value pairs, the from
key, to
key, amount
and fee
:
const formInfo = { "from": "", "to": "", "amount": "", "fee":"" };
When I check the console after sending a transaction, I see the following:
which tells me that it's valid. When I check the backend, however, I see the result of req.body.from
as undefined
in the console:
The code for this route is as follows:
app.post('/add-transaction', (req, res) => {
console.log('requestFrom', req.body.from);
blockModel.find({ $or: [{ from: req.body.from }, { to: req.body.from }, { miner: req.body.from }] }).then((blocks) => {
if (!blocks.length) {
yakhicoin.addBlock(new Block("system", req.body.from, 1000, 0, "null", 0));
const newblock = new blockModel(yakhicoin.getLatestBlock());
newblock.save();
}
let balance = 0;
for (const block of blocks) {
if (block.from == req.body.from) {balance -= (block.amount block.fee);}
if (block.to == req.body.from) {balance = block.amount;}
if (block.miner == req.body.from) {balance = (block.fee block.reward);}
}
if (req.body.amount <= balance || (!blocks.length && req.body.amount <= 1000)) {
const formData = {
"from": req.body.from,
"to": req.body.to,
"amount": req.body.amount,
"fee": req.body.fee
}
const newtransaction = new transactionModel(formData);
newtransaction
.save() // Promise
.then( //resolved...
(success) => {
res.send({"transaction" : success, "error" : 0});
}
)
.catch( //rejected...
(error) => {
res.send({"error" : error});
}
);
}
else
res.json({"error" : 1})
})
})
When I use the same route in POSTMAN, everything works fine:
With the following headers:
I can't see why this error occurs, no matter how often I check it. Why does formInfo
suddenly get received as undefined, when it exists right before sending? I also have cors()
enabled. Any help is appreciated!
CodePudding user response:
Issue is that the body encoding is different in the browser example from the postman example.
The body in your post request should be a string (example below), when using the content-type you are currently using.
fetch(url, {
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: 'from=xxxxx&to=yyyyyy....etc'
})
Or you can change the content-type and stringify the object.
fetch(url, {
method: 'post',
headers: {
Content-Type: 'application/json',
// 'Content-Type': 'application/x-www-form-urlencoded'
},
body: JSON.stringify(formInfo)
})