![](/img/trans.png)
[英]Trying to make a post request in node js but I keep getting an empty body returned
[英]POST Request Body is empty
任务
问题
当我通过fetch
发送数据时,请求body
显示为空。 但是,如果我使用 Postman,我可以发送和查看body
数据。
我添加了一个console.log(req.body)
,它正在将{}
打印到控制台。
解析数据并将其发送到端点
const changeHandler = (event) => {
Papa.parse(event.target.files[0], {
header: true,
skipEmptyLines: true,
complete: function (results) {
results.data.forEach(entry => {
// Create the data object.
let data = {};
let keys = ['Date', 'Description', 'Debit Amount'];
for (let key in entry) {
if (keys.includes(key)) {
data[key.toLowerCase().replaceAll(' ', '_')] = entry[key];
}
}
// Send data to server
fetch('http://localhost:3001/api/create_transactions', {
method: 'POST',
mode: 'no-cors',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
}).then(function (response) {
console.log(response);
})
});
},
});
// Reset file input
event.target.value = null;
};
保存数据到 MySql
app.use(express.json());
const crypto = require('crypto');
app.post("/api/create_transactions", (req, res) => {
console.log(req.body);
/*
let hash = crypto.createHash('md5').update(req.body['date'] + req.body['description'] + req.body['debit_amount']).digest('hex');
let data = [
hash,
req.body['date'],
req.body['description'],
req.body['debit_amount'],
];
db.query('insert into transactions (`hash`, `date`, `description`, `debit_amount`) values (?, ?, ?, ?)', data, (err, result, fields) => {
if (err) {
console.log(err);
} else {
console.log(result);
res.send(JSON.stringify({"status": 200, "error": null, "response": result}))
}
});
*/
});
app.listen(PORT, () => {
console.log(`Server listening on ${PORT}`);
});
根据这篇文章Fetch: post json data, application/json change to text/plain如果您使用的是no-cors
,则不能将Content-Type
更改为application/json
。 所以如果我想使用fetch
就必须启用cors
。
使用本教程https://www.section.io/engineering-education/how-to-use-cors-in-nodejs-with-express/我能够在我的 nodejs 服务器上启用 cors 并接收正确的标头。
尝试使用 express 的 bodyParser app.use(express.bodyParser());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.