Allow CORS between ReactJS and Flask Backend

I’m having an issue with CORS. I’ve implemented my RESTful backend using Flask and the frontend with React JS. When I attempt to make any request by calling an API, I’m blocked by CORS.

This is the API.js file

const APIURL = new URL('http://127.0.0.1:5000/api/');

async function logIn(credentials) {
    let response = await fetch(APIURL + 'login', {
        method: 'POST',
        credentials: 'include',
        headers: {
            'Content-Type': 'application/json',
        },
        body: JSON.stringify(credentials),
    });
    if (response.ok) {
        const user = await response.json();
        return user;
    } else {
        const errDetail = await response.json();
        throw errDetail.message;
    }
}

Server side we have:

main.py:

from src import create_app

app = create_app()

if __name__ == '__main__':
    app.run(debug=True )

init.py:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from os import path
from flask_login import LoginManager
from flask_jwt_extended import JWTManager
from flask_cors import CORS
from dotenv import load_dotenv
import os

load_dotenv()

db = SQLAlchemy()
DB_NAME = "db"
DB_USERNAME = "root"
DB_PASSWORD = "root"


def create_app():
    app = Flask(__name__)
    CORS(app, origins='http://localhost:3000', methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])
    app.config['SECRET_KEY'] = os.getenv("SECRET_KEY")
    app.config['CORS_HEADERS'] = 'Content-Type'
    app.config["JWT_SECRET_KEY"] = os.getenv("JWT_SECRET_KEY")
    app.config['SQLALCHEMY_DATABASE_URI'] = f'mysql://{DB_USERNAME}:{DB_PASSWORD}@localhost/{DB_NAME}'
    app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
    jwt = JWTManager(app)
    db.init_app(app)


    from .views import views
    from .auth import auth

    app.register_blueprint(views, url_prefix='/api')
    app.register_blueprint(auth, url_prefix='/api')

    from .models import User

    with app.app_context():
        db.create_all()

    login_manager = LoginManager()
    login_manager.login_view = 'auth.login'
    login_manager.init_app(app)

    @login_manager.user_loader
    def load_user(id):
        return User.query.get(int(id))

    return app

and auth.py:

from flask import Blueprint, render_template, request, flash, redirect, url_for, jsonify
from flask_cors import cross_origin

from .models import User
from werkzeug.security import generate_password_hash, check_password_hash
from . import db
from flask_login import login_user, login_required, logout_user, current_user
from flask_jwt_extended import create_access_token
from flask_jwt_extended import get_jwt_identity
from flask_jwt_extended import jwt_required

auth = Blueprint('auth', __name__)


@auth.route('/login', methods=['POST', 'OPTIONS'])
def login():
    data = request.json
    print(data)
    email = data.get('email')
    password = data.get('password')

    user = User.query.filter_by(email=email).first()
    if user:
        if check_password_hash(user.password, password):
            access_token = create_access_token(identity=user.pe_id)
            return jsonify(access_token=access_token), 200
        else:
            return jsonify({'error': 'Incorrect user or password, try again.'}), 400
    else:
        return jsonify({'error': 'Incorrect user or password, try again.'}), 400

I continue to obtain this error:

Access to fetch at 'http://127.0.0.1:5000/api/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.

On the server terminal I see:

WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
 * Restarting with stat
 * Debugger is active!
 * Debugger PIN: 134-368-434
127.0.0.1 - - [24/Nov/2023 14:51:38] "OPTIONS /api/login HTTP/1.1" 415 -

I have tryed the simply case reported by doc of flask-cors so i have tried todo that:

def create_app():
    app = Flask(__name__)
    CORS(app)

but nothing changed.
After i tried also to specify more info like that:

def create_app():
    app = Flask(__name__)
    CORS(app, origins='http://localhost:3000', methods=['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'])

but also in this case still nothing.

I have also tried to add OPTIONS method to login api:

@auth.route('/login', methods=['POST', 'OPTIONS'])
def login():

NextJS client component inside page

I am using NextJS 14.
I am building a landing page and for one of the sections I need to use useState.
I marked my component as “use-client” but it still bringing an error that “You’re importing a component that needs useState. It only works in a Client Component but none of its parents are marked with “use client”, so they’re Server Components by default.”

Example of the page:

import { Metadata } from 'next';
import React from 'react';
import Footer from "@/app/components/layout/footer/footer";

export const metadata: Metadata = {
  title: 'NextApp',
  description: 'Generated by create next app',
};

const HomePage = () => (
  <Footer />
);

export default HomePage;

my component:

"use-client";

import { useEffect, useState } from "react";

import classes from './style.module.scss';

const Footer = () => {
  const [value, setValue] = useState();
  return (
    <div>
      <footer className={classes.footer}>test</footer>
    </div>
  );
};

export default Footer;

Canvas redraw does not happen after leaving and returning to a page view

I am creating ticket qrcodes on the fly and attaching them to an ng-repeat in a modal when a user clicks a button to open the modal. It works. If the modal stays open, then every 5 minutes the tickets refresh, deleting the original canvas and reattaching a new one. That works too. If the user closes the modal and reopens the modal, it continues to work as designed- if a canvas drawing exists, delete it and reattach a new one.

But if the user leaves the page view, returns to the page view and reopens the modal the canvas HTML is being generated and being attached properly but the image itself is not there.

I am using this jquery-qrcode in my project: http://jeromeetienne.github.com/jquery-qrcode

The button click code to open the modal and code to generate qrCode :

  $scope.openTicketModal = function() {
    
    // this interval is need to let ng-repeat in modal populate
    // before triggering the genQRCode() function - otherwise, the genQRCode()
    // will create the code and try to attach the `canvas` to the DIV
    // before the div is actually rendered - causing it to fail.

    if ($scope.club.tickets.length > 0) {
      var tik = $scope.club.tickets[$scope.club.tickets.length-1] ;
      var lastTicket = gf.ang("ticketID_"+tik.ticketID) ;
      $scope.ticketInit = $interval(function() {
        // only generate qrCodes after last ticket element has been created in modals ng-repeat
        if (lastTicket) {
          $scope.genQRCode() ;
          $interval.cancel($scope.ticketInit) ;
        }
      },100) ;
      $scope.tixModal.show() ;
    }
  }

  //gf.ang = return angular.element('#elementID')
  //gf.elm = return angular.element('#elementID')[0] ;

  $scope.genQRCode = function() {
    $scope.refreshTickets = 1 ;
    clubService.getTickets($scope.club.cID,$scope.club.clID,$scope.club.ceID)
    .then(function(response) {
      $scope.refreshTickets = 0 ;
      if (response.success == true) {
        for (var x=0;x<response.tickets.length;x++) {
          var ticket = response.tickets[x] ;
          var tikImgDiv = gf.elm('ticketID_'+ticket.ticketID) ;

          // if a canvas already added, then delete it.
          // first element is ghost element to be cloned and used for new canvas

          console.log(tikImgDiv) ;
          console.log('div' +tikImgDiv.children.length) ;
          if (tikImgDiv.children.length > 1) {
            console.log("deleteing clonsed div w/ canvas") ;
            tikImgDiv.removeChild(tikImgDiv.lastChild) ;
          }

          // clone hidden div & use clone to reattach new canvas
          var tikImg = gf.elm('ticketID_img') ;
          var clone = tikImg.cloneNode(true) ;

          //use unique 'tixCounter' to ensure DIV is never cached.
          clone.id = 'ticketID_img_' + $rootScope.tixCounter ;
          clone.style.display = "" ;
          tikImgDiv.appendChild(clone) ;

          if (ticket.ticketRefund == 0) {
            var refund = "No" ;
          } else {
            var refund = "Yes" ;
          }
          $scope.ticketCSS[ticket.ticketID].refunds = refund ;
          $scope.ticketCSS[ticket.ticketID].trans = "No" ;
          $scope.ticketCSS[ticket.ticketID].desc = ticket.ticketDesc ;
          jQuery('#ticketID_img_'+$rootScope.tixCounter).qrcode({width:150,height:150,text:ticket.liveCode}) ;
          $rootScope.tixCounter++ ;
        }
      }
    }) ;

HTML in page view modal:

      <div id="ticketContainer" ng-show="!refreshTickets" class="ticketContainer">
          <div id="ticketID_{{ticket.ticketID}}" class="centerDivContents">
            <div id="ticketID_img" class="centerDivContents" ></div>
          </div>
      </div>

The page state:

  .state('tab.clubs', {
    cache: true,
    url: '/clubs',
    params: tabParams,
    views: {
      'tab-clubs': {
        templateUrl: 'templates/tab-clubs.html',
        controller: 'ClubCtrl'
      }
    }
  })
  .state('tab.club-detail', {
    cache: false,
    url: '/clubs/:ceID',
    params: tabParams,
    views: {
      'tab-clubs': {
        templateUrl: 'templates/detail-clubs.html',
        controller: 'ClubDetailCtrl'
      }
    }
  })

On a side note, if I change the tab.club-detail page cache: true, then everything works just fine…no issues. I don’t know why…and it doesn’t make sense to me as one would think caching would cause more issues. But regardless, I need the page cache: false set for the pageview for a variety of other reasons.

Passing JSON from Flask to Javascript returns empty. How can I let it show the dynamic value?

My app.route:

@app.route('/my_flask_route', methods=['POST'])
def receive_value():
    data = request.get_json()
    return jsonify(status="succes", data=data)

My JS:

document.addEventListener('DOMContentLoaded', function() {
    fetch('/my_flask_route', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({}),
    })
    .then((response) => {
    response.json().then((data) => {
    console.log(data)
    document.getElementById('input_value').value = data.my_dynamic_value;
    })
    .catch(error => console.error('Error fetching value:', error));
    })})

I can see in the developer console that the value I’m looking for is stored as JSON:

{
  "data": {
    "my_dynamic_value": 5.1
  },
  "status": "succes"
}

I just seem to be stuck at passing the value to the JS script to overwrite a spin box in my html. All I see as a result is:

[Log] {data: {}, status: "succes"}

“google is not defined” and “google.maps.LatLng in undefined” errors when using Google Maps Isomorphic Javascript project

I’m trying to use the Google Maps JavaScript API to create a map on my website, but I’m getting two errors: “google is not defined” and “google.maps.LatLng in undefined.” I’ve tried searching for answers to these errors, but I haven’t been able to find a solution.

Below added issue facing screenshots

Screenshot – 1
enter image description here

Screenshot – 2
enter image description here

Screenshot – 3
enter image description here

Screenshot – 4
enter image description here

Navigator issues

I am a beginner in React Native and I want to create the following project:

I have a component called MainContainer, which is a NavigationContainer (Tab.Navigator) with several Tab.Screen components: Home, MenuForTeacher, ScanCode, and Settings.

Within MenuForTeacher, there is another Tab.Navigator, this time using material-top-tabs, with two Tab.Screen components: homeStack and AddForAllClasses.

Inside homeStack, there is a react-navigation-stack with two screens: AddForTeacher (the default screen) and ClassName. I want to add a button in AddForTeacher, so that when it is tapped, ClassName will appear.

I implemented this design because ClassName shouldn’t be part of the MainContainer. Therefore, it doesn’t have the bottom navigation bar but instead, in the header, only a ‘button’ allowing users to navigate back to the AddForTeacher screen.

enter image description here

The issue is :

ERROR  Error: This navigator has both navigation and container props, so it is unclear if it should own its own state. Remove props: "route" if the navigator should get its state from the navigation prop. If the navigator should maintain its own state, do not pass a navigation prop.

*** This project is for learning in React Native, so feel free to provide any critiques. I’m open to feedback as it helps me learn more about this framework.

MainContainer

import {NavigationContainer} from '@react-navigation/native';
import {createBottomTabNavigator} from '@react-navigation/bottom-tabs';
import Icon from 'react-native-vector-icons/Ionicons';
import React,{useContext} from 'react';
import Home from './screens/Home';
import Settings from './screens/Settings';

import ScanCode from './screens/ScanCode';

import {AuthContext} from '../App';
import MenuForTeacher from './screens/screensForTeacher/MenuForTeacher';

const homeName = 'Home';
const settingsName = 'Settings';
const scanCodeName = 'ScanCode';
const menuForTeacher = 'Menu';

const Tab = createBottomTabNavigator();


function MainContainer() {
  const {user} = useContext(AuthContext);
  //const [email, setEmail] = React.useState(Email);
  //console.log("email in MainContainer"+email)
  return (
    <>
    {console.log("maincontainer user"+user)}
    <NavigationContainer>
      <Tab.Navigator
        initialRouteName={homeName}
        screenOptions={({route}) => ({
          tabBarIcon: ({focused, color, size}) => {
            let iconName;

            if (route.name === homeName) {
              iconName = focused ? 'home' : 'home-outline';
            } else if (route.name === settingsName) {
              iconName = focused ? 'settings-sharp' : 'settings-outline';
            } else if (route.name === scanCodeName) {
              iconName = focused ? 'scan' : 'scan';
            }
            else if (route.name === menuForTeacher && user==="teacher") {
              iconName = focused ? 'school' : 'school';
            }

             
            return <Icon name={iconName} size={size} color={color} />;
          },
          tabBarActiveTintColor: '#1A3C40',
          tabBarInactiveTintColor: 'gray',
           
          headerShown: route.name !== homeName ? true : false,
          headerTintColor: '#EDE6DB',
          headerStyle: {
            backgroundColor: '#1D5C63',
          },  
        })}>         
        <Tab.Screen name={homeName} component={Home} />
        {(user==="teacher")?
          (<Tab.Screen name={menuForTeacher} component={MenuForTeacher} />)
        :null}
        <Tab.Screen name={scanCodeName} component={ScanCode} />
        <Tab.Screen name={settingsName} component={Settings} />        
      </Tab.Navigator>
    </NavigationContainer>
    </>
  );
}
export default MainContainer

MenuForTeacher

import {NavigationContainer} from '@react-navigation/native';
import { createMaterialTopTabNavigator } from '@react-navigation/material-top-tabs';
import Icon from 'react-native-vector-icons/Ionicons';
import React,{useContext} from 'react';


import {AuthContext} from '../../../App';

import NavigatorAddForTeacher from "./homeStack";
import AddForAllClasses from "./AddForAllClasses";


const addForTeacher = 'My classes';
const addForAllClasses = 'All classes';

const Tab = createMaterialTopTabNavigator();




function MenuForTeacher() {
  const {user} = useContext(AuthContext);
  return (
    <>
      <Tab.Navigator
        initialRouteName={addForTeacher}
         screenOptions={() => ({
          tabBarActiveTintColor: '#1A3C40',
          tabBarInactiveTintColor: 'gray',
        })}>
        <Tab.Screen name={addForTeacher} component={NavigatorAddForTeacher} />
        <Tab.Screen name={addForAllClasses} component={AddForAllClasses} />
      </Tab.Navigator>
    </>
  );
}
export default MenuForTeacher;

homeStack

import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer} from 'react-navigation';
import AddForTeacher from './AddForTeacher';
import ClassName from './ClassName';

const screens ={
    AddForTeacher:{
        screen: AddForTeacher
    },
    ClassName:{
        screen: ClassName
    }
};

const HomeStack = createStackNavigator(screens);

export default createAppContainer(HomeStack);

AddForTeacher

import {
    Text, View,StyleSheet,TouchableOpacity,ScrollView
  } from 'react-native';

import API_BASE_URL from '../../../../config';
import {AuthContext} from '../../../App';
import React,{useContext, useEffect,useState} from 'react';
import AsyncStorage from '@react-native-async-storage/async-storage';
import Icon from 'react-native-vector-icons/Ionicons';







const AddForTeacher = ({navigation}) =>{
    const {setClassSelectByTeahcer} = useContext(AuthContext);
    const {classSelectByTeahcer} = useContext(AuthContext);
    const {email} = useContext(AuthContext);
    const [classes,setClasses] = useState([]);
    const [isLoading, setIsLoading] = useState(true);

    
    const getJwtTokenFromAsyncStorage = async () => {
        ...
      };

    const fetchClass = async () =>{
        ...
    }

    const handleClassNamePress = (item) => {
      navigation.navigate('ClassName');
    };
    
    useEffect(() => {
      if (isLoading) {
        fetchClass();
      }
    }, [isLoading]);

    return (
      <>
        <ScrollView style={styles.contanerClasses}>
          {classes.map((item, index) => (
            <View key={item.NomeClasse} style={styles.contanerClass}>
              <View style={styles.eatchClass}>
                <Text>{item.NomeClasse}</Text>
              </View>
              <View style={styles.horizontalLine} />
              <View style={styles.content}>
                <TouchableOpacity
                onPress={() => handleClassNamePress(item.NomeClasse)}
                // style={}
                >
                  <View style={styles.buttonAdd}>
                    <Icon name={'add-outline'} size={24} />
                  </View>
                </TouchableOpacity>
              </View>
            </View>
          ))}
        </ScrollView>
      </>
    );

}



const styles = StyleSheet.create({
    content:{
        
    },
    horizontalLine: {
        height: 2,
        backgroundColor: 'black',
        marginVertical: 10,
        marginLeft:5,
        marginRight:5,
    },
    contanerClass:{
        padding:10,
        margin:10,
        borderColor: 'black',
        borderRadius: 20,
        borderWidth: 1, 
    },
    contanerClasses:{
        margin:10,
    },
    eatchClass:{
       // borderColor: 'black',
        //borderRadius: 20,
        //borderWidth: 1, 
        
        //borderBottomWidth: StyleSheet.hairlineWidth,
        //width:"80%",
    }
})
export default AddForTeacher;

ClassName

import { de } from "date-fns/locale"
import { Text } from "react-native"

const ClassName = () =>{
    //const { name } = navigation.params;

  return (
    <View >
      <Text>{"hello"}</Text>
    </View>
  );
}

export default ClassName;

Drawing a timed-cycle in a canvas

I have this code below which should draw cycle based on a timer. It, however, starts and draws the cycle in 3 simultaneous parts. I can’t figure out why and how to get it to draw one smooth cycle:

<!DOCTYPE HTML>
<html>
  <head>
    <title>ColumnCycle Growth</title>
    <style>
      body {
        margin: 0px;
        padding: 0px;
      }
    </style>
  </head>
  <body>
    <canvas id="myCanvas" width="800" height="900"></canvas>
    <script>

window.requestAnimFrame = (function (callback) {
        return window.requestAnimationFrame || window.webkitRequestAnimationFrame || 
        window.mozRequestAnimationFrame || window.oRequestAnimationFrame || 
        window.msRequestAnimationFrame ||
        function (callback) {
            window.setTimeout(callback, 500 / 60);
        };
    })();

var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext('2d');
var data = ['Red,250', 'Blue,530', 'Orange,390', 'Green,190', 'Purple,450', 'Brown,600'];

var myCycle = {
    x: canvas.width / 2,
    y: (canvas.height / 2) - 200,//add to push down
    radius: 10,
    colour: '#8ED6FF'
};

//draw the object first, then animate it
var myTotal = 1810;
var lastend = -Math.PI / 2;
var currentEndAngle = 0;
var currentStartAngle = 0;
var radius = (canvas.height) / 6;

var startAngle = -1 * Math.PI/2;
var endAngle = startAngle + (Math.abs(190) / myTotal);


function drawArc(myVal, myCol) {

    //drawArcFill
    //Arc Parameters: x, y, radius, startingAngle (radians), endingAngle (radians), antiClockwise (boolean)
    endAngle = startAngle + (2 * Math.PI * (Math.abs(myVal) / myTotal));

    ctx.beginPath();
    ctx.moveTo(400, 450);
    ctx.arc(400, 450, (canvas.height / 4), startAngle, endAngle, false);
    ctx.lineWidth = 2.5;
    ctx.closePath();
    ctx.strokeStyle = myCol;
    ctx.stroke();

    startAngle = endAngle;
}

//write static texts
var timer = 100;
function animate(startTime) {

    // update
    var time = (new Date()).getTime() - startTime;
    var linearSpeed = timer;//increase to run faster, decrease to slow down
    // pixels / second
    var newX = linearSpeed * time / (5 * timer);//keep the 1000, it is per second
    var myVal = 0;
    var myName = '';
    var i = 0;

    //draw cycles on the same axis
    for (i = 0; i < data.length; ++i) {
        myCycle.x = 50;//cycles on the same axis
        // Extract the data
        var values = data[i].split(",");
        myName = values[0];
        myVal = values[1];
    
    }

    if (newX <= parseInt(myVal)) {
            drawArc(myVal, myName)
        };
   
    // request new frame
    requestAnimFrame(function () {
        animate(startTime);
    });

}
// wait one second before starting animation
setTimeout(function () {
    var startTime = (new Date()).getTime();
    animate(startTime);
}, timer);

    </script>

  </body>
</html>

Apply loader on “Select All” functionality of SumoSelect library

I am using sumoselect.js for my dropdowns. and i also have loader implemented in my project with id “mainloader”.

Now i want when user click on select all then loader should show i.e $(‘#mainloader’).show() and when sumoselect has selected all options inside dropdown then loader should removed i.e $(‘#mainloader’).hide().

But I am unable to implement this functionlaity. enter image description here

in sumoselect.js i have tried by adding my loader like below

enter image description here

but loader is showing after it is selecting all options but i want it should show instant when clicked on select and it should be hidden when all options are selected.

Owl Carousel 2 with video html – set the same height all items

I want use video html in owl carousel with 1 item on screen.

I want set equal height for every item but autoHeight not working with tag video html. I found this solution but still not working if video is first slide.

https://stackoverflow.com/a/30057129/22415842

My example looks like this

Owl Carousel 2 – autoHeight (multiple items)

Does anyone know how to implement this solution for video in the owl element regardless of whether the video comes first or does anyone have any solution for this?

Devextreme JS – How to draw a line between 2 markers?

I am using javascript devextreme. I want to draw a line between 2 markers. (Not the route) But I was not successful. I need to draw 2 lines as in the example picture. Devextreme JS – How to draw a line between 2 markers?

$(() => {
  const markerUrl = 'https://js.devexpress.com/Demos/WidgetsGallery/JSDemos/images/maps/map-marker.png';
  const markersData = [{
    location: [40.755833, -73.986389],
    tooltip: {
      text: 'Times Square',
    },
  }, {
    location: '40.7825, -73.966111',
    tooltip: {
      text: 'Central Park',
    },
  }, {
    location: { lat: 40.753889, lng: -73.981389 },
    tooltip: {
      text: 'Fifth Avenue',
    },
  }, {
    location: 'Brooklyn Bridge,New York,NY',
    tooltip: {
      text: 'Brooklyn Bridge',
    },
  },
  ];

  const mapWidget = $('#map').dxMap({
    provider: 'bing',
    apiKey: {
      bing: 'Aq3LKP2BOmzWY47TZoT1YdieypN_rB6RY9FqBfx-MDCKjvvWBbT68R51xwbL-AqC',
    },
    zoom: 11,
    height: 440,
    width: '100%',
    controls: true,
    markerIconSrc: markerUrl,
    markers: markersData,
  }).dxMap('instance');

 
});

The Number() function adds 1 to the numeric result by converting a string to a number

I wanted to convert the string '9333852702227987' into a number with the help of the Number() function when I realized that the output was plus one.

I tried using other methods to convert the string value that contains the mentioned number into a number value, but I still faced the same problem.

let convertToString = function (num1) {
    console.log(Number(num1))
    console.log(parseInt(num1))
    console.log(num1 * 1)
    console.log(Math.round(num1))
    console.log(Math.floor(num1))
    console.log(Math.ceil(num1))
    console.log('All results of the ways to convert a string into a number are wrong!!!')
};

convertToString('9333852702227987')


// The result of all of them is: 9333852702227988

Do you know the reason for this?

Script stops working console dont give error (Beginner)

Currently, I am working on a card game as a home project. All the logic of the game has been implemented and is working.

Now I made an animation for dice rolling and the revealing of the cards. It looks like it’s working but in a random(?) moment the script stops working.

It probably a small thing I don’t see so that the reason I posted it here maybe someone can take a fresh look at it.

var highlightedCard;
var selectedIndices = [];


// Get the "Roll Dice" button element
var rollDiceButton = document.getElementById("rollDiceButton");
let canRollDice = true; // Flag to track if dice can be rolled

document.addEventListener('DOMContentLoaded', function() {
  // Add your event listeners here
  document.body.addEventListener("click", function() {
    if (canRollDice) {
      rollDice();
    } else {
      revealCard();
    }
  });

  // Other event listeners or initialization code
});

function rollDice() {
  if (highlightedCard || !canRollDice) {
    return; // Exit the function if a card is still highlighted or dice can't be rolled
  }

  canRollDice = false; // Disable rolling until revealCard is used

  var dice1 = document.getElementById("dice1");
  var dice2 = document.getElementById("dice2");

  // Apply the "roll" class to initiate the rolling animation
  dice1.classList.add("dice");
  dice2.classList.add("dice");

  // Create an array with the file names of all 6 possible dice faces
  var diceFaces = ["nummer1.PNG", "nummer2.PNG", "nummer3.PNG", "nummer4.PNG", "nummer5.PNG", "nummer6.PNG"];

  // Shuffle the diceFaces array
  shuffleArray(diceFaces);

  // Function to shuffle an array
  function shuffleArray(array) {
    for (var i = array.length - 1; i > 0; i--) {
      var j = Math.floor(Math.random() * (i + 1));
      var temp = array[i];
      array[i] = array[j];
      array[j] = temp;
    }
  }

  // Switch dice images during the animation
  for (let i = 0; i < diceFaces.length; i++) {
    setTimeout(() => {
      dice1.src = diceFaces[i];
      dice2.src = diceFaces[i];
    }, i * 250); // Switch every 250 milliseconds, adjust the timing as needed
  }

  // After switching all faces, randomly select the final face
  setTimeout(() => {
    var result1 = Math.floor(Math.random() * 6) + 1;
    var result2 = Math.floor(Math.random() * 6) + 1;

    dice1.src = `nummer${result2}.PNG`;
    dice2.src = `nummer${result1}.PNG`;

    // Calculate the index based on the original axis
    var selectedIndex = (result1 - 1) * 6 + (6 - result2) + 1;
    console.log(selectedIndex);

    // Check if the selected index has already been selected
    while (selectedIndices.includes(selectedIndex)) {
      // Move to the next index
      selectedIndex = (selectedIndex % 36) + 1; // Assuming 36 cards in total
    }

    var selectedCard = document.getElementById(`card-${selectedIndex}`);

    if (selectedCard) {
      // Highlight the selected card
      selectedCard.classList.add("selected");

      // Set the highlighted card
      highlightedCard = selectedCard;

      // Show the "Reveal Card" button
      revealCardButton.style.display = "none";

      // Add the index to the selected indices list
      selectedIndices.push(selectedIndex);

      console.log(selectedIndices);

      // Remove the "dice" class to reset the animation for the next roll
      setTimeout(() => {
        dice1.classList.remove("dice");
        dice2.classList.remove("dice");

        canRollDice = true; // Enable rolling for the next roll
      }, 1500); // Adjust the timing to match the animation duration
    }
  }, diceFaces.length * 250); // Adjust the timing to match the animation duration
}

revealCardButton.addEventListener("click", revealCard);

function revealCard() {
  console.log("Before reveal: ", highlightedCard);

  if (highlightedCard) {
    handleCardClick(highlightedCard);

    console.log("After handleCardClick: ", highlightedCard);

    // Remove the highlight class
    highlightedCard.classList.remove("selected");

    // Reset the highlighted card variable
    highlightedCard = null;

    console.log("After reset: ", highlightedCard);

    // Hide the "Reveal Card" button
    revealCardButton.style.display = "none";

    // Reset canRollDice to true
    canRollDice = true;
  }
}
@keyframes roll {
  0% {
    transform: rotate(0deg) rotateX(0deg) translateY(0);
  }
  20% {
    transform: rotate(180deg) rotateX(180deg) translateY(-20px);
  }
  40% {
    transform: rotate(360deg) rotateX(0deg) translateY(0);
  }
  60% {
    transform: rotate(540deg) rotateX(180deg) translateY(-20px);
  }
  80% {
    transform: rotate(720deg) rotateX(0deg) translateY(0);
  }
  100% {
    transform: rotate(900deg) rotateX(180deg) translateY(-20px);
  }
}

.dice {
  animation: roll 1.5s cubic-bezier(0.42, 0, 0.58, 1);
}
<!DOCTYPE html>
<html>

<head>
  <link href="styles10.css" rel="stylesheet">
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.6.0/css/bootstrap.min.css">
  <title>Goudzoeken</title>
  <style>

  </style>
</head>

<body>
  <div class="grid-container">
    <div class="deck-container" id="deck-container"></div>
    <div class="container-wrapper" id="none">
      <div class="controls-container">
        <button id="rollDiceButton">Roll Dice</button>
        <button id="revealCardButton" style="display:none;">Reveal Card Color</button>
      </div>
      <div class="dice-container">
        <img id="dice1" class="dice-image" src="nummer1.PNG" alt="Dice 1">
        <img id="dice2" class="dice-image" src="nummer1.PNG" alt="Dice 1">
      </div>
    </div>
  </div>

The console

The field

The goal is that the dice will give a coordinate on the grid.
When clicked on the screen it rolls the dice and the outcome will highlight a card.

These cards will be revealed on the next click. if a pawn (beerglass) is on the revealed card it should move to another position possibly following the rules of the script.

Unfortunately, the script is stopping in for me at random moments

How to confirm payment on stripe for cards which has 3DS Auth

I’m try to handle the customer flow who go thorough the checkout session by entering the 3D credit card but not able to verify the authentication

For some cards next_action has redirect URL but for 3DS card we don’t have the URL – Can someone help how can we authenticate such user

      "type": "use_stripe_sdk",
      "use_stripe_sdk": {
        "directory_server_encryption": {
          "algorithm": "RSA",
          "certificate": "-----BEGIN CERTIFICATE-----nBNY-----END CERTIFICATE-----n",
          "directory_server_id": "A0XXX4",
          "key_id": "3c5ed8002388",
          "root_certificate_authorities": [
            "-----BEGIN CERTIFICATE-----nMIX+9DBw==n-----END CERTIFICATE-----n"
          ]
        },```

error: invalid input syntax for type json when submitting converted circular structure

I haven’t encountered anything like this before. I have a NextJS 13 project, using PostgreSQL.

Initially when submitting the data through the API route, I was getting the “TypeError: Converting circular structure to JSON.”

So I found a function to convert the circular function, which seemed to work.

const getCircularReplacer = () => {
      const seen = new WeakSet();
      return (key, value) => {
        if (typeof value === 'object' && value !== null) {
          if (seen.has(value)) {
            return;
          }
          seen.add(value);
        }
        return value;
      };
    };

This is where I get the invalid input syntax for type json.

Here is my patch function:

export async function PATCH(request: Request) {
  const body = await request.json()
  const {databaseId, boardStatus, updatedTasks} = body;

  try {
    const query = 'Update boards SET status = $1, tasks = $2 WHERE id = $3';
    const values = [boardStatus, updatedTasks, databaseId];
    const result = await conn.query(query, values);

    return NextResponse.json(result);
  } catch (error) {
    console.log(error)
    throw new Error('Failed to update task')
  }
}

So when I console log the individual values I get the value first but then secondary it logs null.

So “boardStatus” first logs the string “Now”, which is correct but then right after undefined.

“updatedTasks” logs and array with two objects (the tasks) but then immediately [null, null]

“databaseId” is a strange one. It logs the number 7 but then logs the following:

{
  _reactName: 'onSubmit',
  _targetInst: null,
  type: 'submit',
  nativeEvent: { isTrusted: true },
  target: {
    '0': {
      '__reactFiber$j2ruhtxtfqr': [Object],
      '__reactEvents$j2ruhtxtfqr': {},
      value: 'Launch version one',
      _valueTracker: {}
    }
  },
  eventPhase: 3,
  bubbles: true,
  cancelable: true,
  timeStamp: 152898.19999992847,
  defaultPrevented: false,
  isTrusted: true
}

I get two errors. Error one seems to point to a problem with the structure of the data but it looks ok to me.

length: 242,
  severity: 'ERROR',
  code: '22P02',
  detail: 'Expected ":", but found ",".',
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: 'JSON data, line 1: ...se}],\"description\":\"Test save to database\"}",...n' +
    "unnamed portal parameter $2 = '...'",
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'jsonfuncs.c',
  line: '646',
  routine: 'json_errsave_error'

Error two is trying to process the secondary [null, null]. I don’t know where this is coming from, unless converting the circular structure did this.

length: 191,
  severity: 'ERROR',
  code: '22P02',
  detail: 'Token "NULL" is invalid.',
  hint: undefined,
  position: undefined,
  internalPosition: undefined,
  internalQuery: undefined,
  where: "JSON data, line 1: {NULL...nunnamed portal parameter $2 = '...'",
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'jsonfuncs.c',
  line: '646',
  routine: 'json_errsave_error'
}

Here is the console.log of the tasks, which is where it seems to hang up:

[
  {
    title: 'Launch version one',
    status: '',
    subtasks: [ [Object], [Object] ],
    description: 'Test save to database'
  },
  {
    title: 'Review early feedback and plan next steps for roadmap',
    status: '',
    subtasks: [ [Object], [Object], [Object] ],
    description: "Beyond the initial launch, we're keeping the initial roadmap completely empty. This meeting will help us plan out our next steps based on actual customer feedback."
  }
]
[ null, null ]

Thanks much for any direction!