POST请求正文为空



任务

  • 分析CSV文件
  • 将数据发送到API端点
  • 将数据保存到MySql数据库

问题

当我通过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}`);
});

根据这个post Fetch:post json数据,application/json更改为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的bodyParserapp.use(express.bodyParser());

最新更新