Is there a way to transfer a value from my JavaScript game directly into a Flask database?

Currently, I am working on developing a JavaScript game embedded in a website that utilizes a Flask database.

For some added context, my goal is to allow users to earn virtual currency, known as Lamocoins, by playing the mini-game. However, I seem to be facing challenges in implementing this feature effectively with the current coding approach.

Below are the snippets of code:

minigame.js

function handleGameOver(){
    ctx.fillStyle = 'black';
    ctx.fillText('GAME OVER', 270, 230);
    ctx.fillText('You have earned ' + 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);
    });
}

Disclaimer: This function is triggered upon collision with an enemy and not connected to any button.

app.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()

Here's a snapshot of the database for reference:

Thank you in advance for addressing my query!

Answer №1

Fetch API requires the "body" to be in the form of a string or an equivalent, but you are supplying it as an object.

In order to send JSON data to the server correctly, you must convert the object into a JSON string:

function handleGameOver(){
    ctx.fillStyle = 'black';
    ctx.fillText('GAME OVER', 270, 230);
    ctx.fillText('You have earned ' + score*2 + ' points!', 70, 300);
    gameOver = true;
    fetch('/update-score', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: json.stringify({'score': score}),
    })
    .then(response => {
            setTimeout(() => {
                location.reload();
            }, 1000);
    })
    .catch(error => {
        console.error(error);
    });
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Gmail with Nodemailer is throwing an error: "Cannot add property 'mailer' on a string with value 'SMTP'."

I am facing an issue with sending data from a form to my Gmail account. Whenever I click the submit button, I encounter the same error message repeatedly. Despite researching various problems related to nodemailer, none of them match the specific problem t ...

Guide to building a React site that showcases customized content from users in a visually appealing way

Imagine you're designing a website where users can share their writing, whether it's a blog, a platform like Medium, or even StackOverflow. You want to allow users to format text with bold and italic styles, insert pictures within the text, and m ...

Unable to upload gathered email to Mailchimp mailing list through Nodejs and express API

Seeking guidance on integrating data collection with Mailchimp in a Nodejs backend project. I am currently working on an email signup list page where users input their first name, last name, and email. The HTML file contains fields named firstName, lastN ...

Generate pairs of arrays using elements from two separate arrays

I have two arrays containing IDs that are related in length. When I say they are related in length, I mean that if ArrayA has a length of 4, then ArrayB will have a length equal to (ArrayA.length * (ArrayA.length - 1)) / 2 (which means if ArrayA has a leng ...

Is the code failing to refresh the browser when the file is modified?

Does anyone know how to reload the browser when a file changes? var changing = require('changing'); var watcher = changing( { interval: '0s' }); watcher.add("/home/diegonode/Desktop/ExpressCart-master/routes/2.mk"); watcher.on(& ...

Webstorm encounters difficulties compiling Sass

While attempting to utilize Sass in the Webstorm IDE, I noticed that it is defaulting to Ruby 1.8 (OS Default) instead of my preferred RVM Ruby Version (1.9.x). To address this issue, I tried setting the path for Sass in the Watcher-Configuration: PATH=$ ...

Is it possible to utilize npm packages within a standard web page without any frameworks or libraries?

I am currently working on a basic website created using vanilla HTML, CSS, and JS files. My goal is to incorporate the import { moment } from "moment" syntax into my JS files. However, after adding npm to my project, installing moment with npm i ...

A guide on extracting JSON data from a script tag using Cheerio

I am in the process of extracting metadata from various websites. While utilizing Cheerio to retrieve elements like $('meta[property="article:published_time"]').attr('content') works smoothly for most sites, there are some whe ...

Watch YouTube videos without having to open a new tab

When I open the href link in this fiddle in a new tab by using ctrl + click: https://jsfiddle.net/fNPvf/30636/, the video is opened in a new tab but does not play unless I give focus to that tab. How can I make the youtube video play automatically when ope ...

Exploring the depths of a multi-level JSON array in JavaScript

My asp.net web service has the capability to return a multi-level array. To parse the json string, I am using the json2.js library : var data = JSON.parse(msg.d); The first level of parsing is successful, but the second level array (data) remains as an ...

Manipulating front matter metadata when reading/writing a markdown file in Node.js

I have a large collection of markdown files that I need to update by adding new data to their front matter metadata. Currently, the file structure looks like this: --- title: My title here --- Markdown content here My goal is to include an id property ...

Can you explain why this overtime total is not being calculated accurately?

Here's a scenario: A parking garage charges $5.00 to park for up to three hours. After that, they add $1.50 per hour for every additional hour or part thereof. The maximum charge within 24 hours is $18.00. We're assuming no car stays longer than ...

Center the div vertically aligned with the following element

Seeking guidance on aligning an element to the vertical center of another element. https://i.sstatic.net/Hk8UE.png In the provided scenario, the goal is to align the top of text with the vertical center of the adjacent image. https://i.sstatic.net/hxmm9 ...

Ensure there is a sufficient gap between the top and bottom icons within the Material-UI Drawer

I'm having difficulty articulating this, but I'd like to add two different sets of icons to the Drawer component. Set 1 should be displayed at the top in a standard column format, similar to the examples provided by them. Set 2 should go at the b ...

What causes the appearance of echo messages in my JSON response and what steps can I take to stop them from displaying in the browser console?

I have the following PHP code: <?php header("Access-Control-Allow-Origin: *"); include_once('../includes/mysql_connect.php'); include_once('../db/tables/search.php'); // SAVE TO DB $search = new search($mysql); //$search- ...

Continue looping after completing the previous task

My current challenge involves utilizing a for loop in puppeteer. The issue is that it opens 11 chromium instances simultaneously, leading to a server crash. I am seeking alternative approaches to ensure that the loop only progresses after the previous it ...

Creating a mouseover popup window for a specific text citation based on its ID using JavaScript in XSLT

I have implemented the following XML code for citations related to figures, tables, and reference citations. When hovering over the citation, it should display the relevant text based on the id and href. XML code for Citation: Fig. <link href="#ecog34 ...

Prevent the display of cascading div elements by using JavaScript and jQuery scripting

My webpage performs a simple check to verify if Javascript and cookies are enabled on the client's browser. If they are enabled, the script displays the content inside div id="conteudo" and hides the warning message inside div id="aviso". If not, the ...

Unable to modify the array while attempting to incorporate additional features

My form consists of a set of fields that need to be submitted to the backend upon completion. These fields can be dynamically added through the "add more" functionality. View Code Fiddle For instance, if I use the "add more" feature three times, the valu ...

Leveraging functions and callback within Node.js

Struggling with node.js and function calls here. The issue is that when I call a function, node.js doesn't wait for it to complete, resulting in empty return values. Below is the code snippet: exports.handle = (event, context,callback) => { switch ...