我正在尝试将一个整数发送到后端,以使用 React
中的 axios
执行一些计算。但是,在后端,我得到了 [object object]
。我尝试通过执行 console.log(Object.getOwnPropertyNames(req.body))
来查看对象中的内容,它返回空对象
我也在使用正文解析器。我的另一条路线是使用 axios 发送数据(对象),它工作得很好。在body.parse中integer不被视为纯整数吗?
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();
});*/
});
});
我的 react :
handleSubmit(e){
e.preventDefault()
var remain = this.state.wallet - this.state.total
console.log(remain)
axios({ method: 'post', url: '/buy', data: remain})
}
最佳答案
一般来说,数字、 bool 值、字符串和没有任何对象或数组的 null 都是有效的 json。但 axios 在自动检测过程中默认不会将这些视为 JSON,只有那些 typeof
等于 object
的内容才会以内容类型 application/json
发送。
您需要自己设置content-type
header :
axios({ method: 'post', url: '/buy', data: 1, headers: {
'Content-Type': 'application/json; charset=utf-8'
}})
现在 axios 将发送“正确”内容类型 header ,以便接收者将其视为 JSON。
但是现在 body-parser
会提示收到的数据不是有效的 json。这是因为以下选项:
strict
When set totrue
, will only accept arrays and objects; whenfalse
will accept anythingJSON.parse
accepts. Defaults totrue
.
您的代码可以将 body-parser
的选项 strict: false
与 axios
的 Content-Type
header 设置结合使用。
所以可以让它工作,但最简单的方法是将整数包装到一个对象中。
关于javascript - React.js 使用 axios 发送整数数据但在 Node.js 中获取 [object object],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52614462/