I am trying to send an integer to the backend to perform some calculations using axios in React. However, In the backend, I got [object object] instead. I tried to see what is in the object by doing console.log(Object.getOwnPropertyNames(req.body)) and it returns empty object
I am using body parser as well. My other route is using axios to send data(object), it worked fine. Is integer not regard as the pure integer in body.parse?
const express = require('express');
const app = express();
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.post('/buy', (req, res) => {
MongoClient.connect(url, { useNewUrlParser: true }, function(err, db) {
if (err) throw err;
var dbo = db.db("wallet");
var myquery = { amount: {$gt: 0} }
console.log("New Amount:" + req.body)
console.log(Object.getOwnPropertyNames(req.body))
var newquery = { $set: {amount: req.body}}
/*dbo.collection("account").updateOne(myquery, newquery, function(err, re) {
if (err) throw err;
console.log("Wallet updated")
db.close();
});*/
});
});
My react:
handleSubmit(e){
e.preventDefault()
var remain = this.state.wallet - this.state.total
console.log(remain)
axios({ method: 'post', url: '/buy', data: remain})
}
In generally also numbers, boolean, strings and null without any object or array around are valid json. But axios does not treat those as JSON by default in its auto detection process, only those with typeof being equal to object will be send with the content type application/json.
You would need to set the content-type header yourself:
axios({ method: 'post', url: '/buy', data: 1, headers: {
'Content-Type': 'application/json; charset=utf-8'
}})
Now axios would send with the "correct" content type header so that the receiver will treat it as JSON.
But now the body-parser would complain about the received data not beeing valid json. That's because of the following option:
strict
When set totrue, will only accept arrays and objects; whenfalsewill accept anythingJSON.parseaccepts. Defaults totrue.
Your code would work using the option strict: false for body-parser in combination with the Content-Type header settings for axios.
So it is possible to get it work, but the easiest way would be wrapping the integer into an object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With