我目前正在使用 Flask 数据库的网站中编写 Javascript 游戏。
添加一些背景信息:我正在尝试这样做,以便用户能够通过玩迷你游戏来获得货币(名为 Lamocoins)。但是,它似乎不适用于我尝试编码的当前方式。
以下是代码:
小游戏.js
function handleGameOver(){
ctx.fillStyle = 'black';
ctx.fillText('GAME OVER', 270, 230);
ctx.fillText('You have gained ' + score*2 + ' Lamocoins!', 70, 300);
gameOver = true;
fetch('/gain_currency', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: {'score': score},
})
.then(response => {
setTimeout(() => {
location.reload();
}, 1000);
})
.catch(error => {
console.error(error);
});
}
注意:此功能未连接到按钮。每当玩家与敌人碰撞时就会发生。
应用程序.py
@app.route('/gain_currency', methods=['POST'])
@login_required
def gain_currency():
data = request.get_json()
score = data['score']
current_user.currency_balance += score
db.session.commit()
这是数据库的图片(如果有帮助的话):
提前感谢您回答我的问题!
Fetch API 期望您的“主体”是字符串或等效内容。你正在向它提供一个对象。
要正确将 JSON 数据提交到服务器,您需要将对象字符串化为 JSON 字符串:
function handleGameOver(){
ctx.fillStyle = 'black';
ctx.fillText('GAME OVER', 270, 230);
ctx.fillText('You have gained ' + score*2 + ' Lamocoins!', 70, 300);
gameOver = true;
fetch('/gain_currency', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: json.stringify({'score': score}),
})
.then(response => {
setTimeout(() => {
location.reload();
}, 1000);
})
.catch(error => {
console.error(error);
});
}