【发布时间】:2020-01-02 17:51:27
【问题描述】:
我正在尝试使用 fetch POST 请求将数据从我的客户端应用程序发送到我的 API。我使用的堆栈是 React、Express、NodeJS 和 MySQL。我已经验证直接在 express 中使用示例数据会将数据插入到数据库中。但是我的客户端 POST 请求似乎不起作用。这是用户点击提交时触发的代码(React)
handleSubmit(){
var data = {
//Production data
// gameTypeID : this.state.gameTypeID,
// gameHostID : this.state.gameHostID,
// buyInAmount : this.state.monBuyInAmount,
// earningSystem : this.state.earningSystemID,
// customCode : this.state.customCode,
// gameStatus : 1,
// mapID : this.state.MapID
//Sample data
gameTypeID : 1,
gameHostID : 1,
buyInAmount : 3,
earningSystem : 1,
customCode : '',
gameStatus : 1,
mapID : 2
}
fetch('https://localhost:3001/game', {
method: 'post',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({data})
}).then(function(response) {
return response.json()
}).catch(error=>console.log(error))
}
以下是处理 API 请求的快速路由文件。我已经直接在文件中使用相同的样本数据对此进行了测试,并且效果很好。
function create_game(req,res) {
pool.getConnection(function(err, connection){
if(err) {
connection.release();
res.json({"code": 100, "status": "Error in database connection"});
return;
}
let sql ="INSERT INTO games (intGameTypeID, intGameHostID, monBuyInAmount, intEarningSystemID, strCustomCode, intGameStatusID, intMapID) VALUES (?, ?, ?, ?, ?, ?, ?) ";
let gameType = request.body.gameTypeID;
let gameHost = request.body.gameHostID;
let buyIn = request.body.buyInAmount;
let earningSystemID = request.body.earningSystem;
let customCode = request.body.customCode;
let gameStatus = request.body.gameStatus;
let mapID= request.body.mapID
let values = [gameType, gameHost, buyIn, earningSystemID, customCode, gameStatus, mapID];
console.log("connected as id '" + connection.threadId);
console.log("here")
connection.query(sql, values, function(err, result, fields) {
connection.release();
if(!err) {
console.log(result);
}else console.log(err);
});
connection.on('error', function(err){
res.json({"code": 100, "status": "Error in database connection"});
})
})
};
router.post('/create', function(req, res){
create_game(req, res);
});
【问题讨论】:
-
你遇到什么错误了吗?
-
没有一个我能抓到。
标签: node.js reactjs express post