任务
- 解析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}`);
});
2条答案
按热度按时间7lrncoxx1#
根据这篇文章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并接收正确的头。
h6my8fg22#
尝试使用express的bodyParser
app.use(express.bodyParser());