My start button on my 2d runner game wont work after i implemented difficulty selection

I’m making a simple 2d endless runner game for a project. The game is simple, it has one infinitely repeating obstacle and is supposed to have 3 difficulty levels that the player can choose. The score starts at 0 and the score updates when collision is detected above the obstacle and ends the game when the player hits the obstacle. (thanks to kikon for helping i modified your code a little)

I do have some other problems with my code I need to fix as well, but all help is appreciated so if any of you seeing this spot any other errors or questionable logic other than what I’m asking help for then please let me know.

Very sorry if it’s just a small syntax error I missed. Here’s the code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Endless Runner Game</title>
    <link rel="stylesheet" href="style.css">
    <link rel="stylesheet" href="w3.css">
</head>
<body>
    <div id="main-page" class="w3-container">
        <h1 class="">Cube Runner 2D</h1>
        <p>Cube Runner 2D is an endless 2D runner game in where the object of the game is to get 
            your score as high as possible before you run into the obstacle (you die).
        </p>
        <p>The game has <span style="font-weight: bold;">Three Difficulty levels </span>you can choose from below, 
            <span class="w3-text-green" style="font-weight: bold;">Easy, </span>
            <span class="w3-text-yellow" style="font-weight: bold;">Medium, </span>and 
            <span class="w3-text-red" style="font-weight: bold;">Hard.</span></p>


        <div id="difficulty-buttons">
            <button onclick="setDifficulty('easy')" class="w3-green">Easy</button>
            <button onclick="setDifficulty('medium')" class="w3-yellow">Medium</button>
            <button onclick="setDifficulty('hard')" class="w3-red">Hard</button>
        </div>

        <button id="start-button" class="w3-display-middle">Start Game</button>
    </div>

    <div id="game-container">
        <div id="player"></div>
        <div id="obstacle"></div>
        <div id="score">Score: <span id="score-value">-1</span></div>
        <script src="script.js"></script>
    </div>
</body>
</html>
body {
    margin: 0;
    overflow: hidden;
}

#main-page {
    z-index: 1;
}

#game-container { 
    position: absolute;
    width: 100%;
    height: 100vh;
    opacity: 0;
    transition: opacity 2s ease-in-out;
    background-image: url('background.jpg');
    background-repeat: no-repeat;
    background-size: big;
    background-position: center center;
}

/*for game container fade in */

#game-container.visible {
    opacity: 1;
}

/*stuff for main elements of the game*/

#player { 
    position: absolute;
    bottom: 0;
    left: 50px;
    width: 50px; 
    height: 50px;
    background-color: pink;
}

#obstacle { 
    position: absolute;
    bottom: 0; right: 0;
    width: 50px; height: 50px;
    background-color: grey;
}

#score { 
    position: relative;
    top: 15px; 
    left: 10px;
    font-size: 25px;
    text-align: center;
    font-family: sans-serif;
    color: aliceblue;
}

/*for jump*/
.jump { 
    transform: translateY(-100px);
}

/*for the main page div to fade out*/

.fade-out-up {
    animation: fadeOutUp 1s forwards;
}

@keyframes fadeOutUp {
    0% {
        opacity: 1;
        transform: translateY(0);
    }
    100% {
        opacity: 0;
        transform: translateY(-20px);
    }
}

/*for difficulty selectors */

.button-selected {
    transform: scale(0.9);
}
const player = document.getElementById('player');
const obstacle = document.getElementById('obstacle');
const scoreValue = document.getElementById('score-value');
let score = 0;
let gameRunning = false;
let hasJumpedOver = false;

function updateScore() {
    score++;
    scoreValue.innerText = score;
}

function gameOver() {
    gameRunning = false;
    alert('Game Over! Your score is ' + score);
}

function moveObstacle() {
    if (!gameRunning) return;

    let obstaclePosition = parseInt(window.getComputedStyle(obstacle).getPropertyValue('right')) + speed;

    if (obstaclePosition < window.innerWidth) { 
        obstacle.style.right = `${obstaclePosition + speed}px`;
    } else {
        obstacle.style.right = '0';
        hasJumpedOver = false; // Reset this flag when the obstacle resets
    }

    detectCollision();
}

function jump() {
    if (!player.classList.contains('jump')) {
        player.classList.add('jump');

        setTimeout(() => {
             player.classList.remove('jump');
        }, 500);
    }
}

function detectCollision() {
    let playerRect = player.getBoundingClientRect();
    let obstacleRect = obstacle.getBoundingClientRect();

    if (playerRect.left < obstacleRect.right &&
        playerRect.right > obstacleRect.left &&
        playerRect.top < obstacleRect.bottom &&
        playerRect.bottom > obstacleRect.top) {
        // Collision detected, end the game
        gameOver();
    } else if (playerRect.right < obstacleRect.left && !hasJumpedOver) {
        // Player has successfully jumped over the obstacle
        hasJumpedOver = true;
        updateScore();
    }
}

document.addEventListener('keydown', (event) => {
    if (event.code === 'Space') {
        jump();
    }
});

setInterval(moveObstacle, 20);

const difficultyButtons = document.querySelectorAll('#difficulty-buttons button');

difficultyButtons.forEach(button => {
    button.addEventListener('click', function() {
        // remove selected class from all buttons
        difficultyButtons.forEach(btn => {
            btn.classList.remove('button-selected');
        });

        // add the selected class to clicked button
        this.classList.add('button-selected');
    });
});


// misc code for fade in and out on same page

document.getElementById('start-button').addEventListener('click', function() {
    document.getElementById('game-container').classList.add('visible');
    document.getElementById('main-page').classList.add('fade-out-up');
    gameRunning = true; // game starts when start button gets clicked
});

Deck.gl terrain + simple mesh layer

In my project, Deck is used to visualize the earth’s surface.gl and it is also required to place 3D models of the TerrainLayer surface, taking into account the height of the tile.Is there a way to do this, and if so, how?

I tried using the Terrain Extension from the Deck package.gl in conjunction with SimpleMeshLayer, but it did not bring the desired effect.

Unable to access Chart.Js library from npm package install

For context I am building a web application that logs hours spent on certain skills or activities and then displays this data back to the user via a bar graph using Chart.js. I am able to successfully display a mock graph when I used the CDNJS however I would like to avoid using CDNJS if possible. I have installed chart.js packages via npm install and double checked installation was successful by verifying it was in the package.json.

This is what my current WORKING mainpage looks like:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Main Page</title>
    <!-- Reference Chart.js from cdnjs -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/4.4.1/chart.umd.js"></script>
</head>
<body>
    <h1>Main Page</h1>
    <!-- Your main page content here -->

    <!-- Canvas element for the chart -->
    <canvas id="hoursChart" width="400" height="400"></canvas>

    <!-- Button to add logged hours -->
    <button onclick="addLoggedHours()">Add Logged Hours</button>

    <!-- Button to add new skills -->
    <button onclick="addNewSkill()">Add New Skill</button>

    <script>
        //Function to initialize and update the chart
        function updateChart(data) {
            var ctx = document.getElementById('hoursChart').getContext('2d');
            var myChart = new Chart(ctx, {
                type: 'bar',
                data: {
                    labels: data.labels,
                    datasets: [{
                        label: 'Logged Hours',
                        data: data.hours,
                        backgroundColor: 'rgba(75, 192, 192, 0.2)',
                        borderColor: 'rgba(75, 192, 192, 1)',
                        borderWidth: 1
                    }]
                },
                options: {
                    scales: {
                        yAxes: [{
                            ticks: {
                                beginAtZero: true
                            }
                        }]
                    }
                }
            });
        }
        // Sample data for the chart
        var sampleData = {
            labels: ['Skill 1', 'Skill 2', 'Skill 3'],
            hours: [10, 20, 30] // Sample hours logged for each skill
        }

        // Call updateChart function with sample data
        updateChart(sampleData);

        // Need to add function that adds new logged hours

        // Need to add function that adds a new skill to graph
    </script>
</body>
</html>

Along with my WORKING app.js(only including the relevant portions… can include full app.js file if needed):

const express = require('express');
const exphbs = require('express-handlebars');
const path = require('path');

const app = express();

app.engine('.hbs', exphbs.engine({
    extname: '.hbs',
    defaultLayout: 'main', // Main layout file
    layoutsDir: path.join(__dirname, '..', 'frontend', 'views', 'layouts'),
    partialsDir: path.join(__dirname, '..', 'frontend', 'views', 'partials')
}));
app.set('view engine', '.hbs');
app.set('views', path.join(__dirname, '..', 'frontend', 'views'));

// Serve static files (CSS, Javascript, etc.)
app.use(express.static(path.join(__dirname, '..', 'frontend')));

// Define Routes
app.get('/main', (req,res) => {
    res.render('mainpage');
});

But I’m wondering if there is anyway to avoid using CDNJS and being able to access the chart.js library directly from the node_modules where it is downloaded.

I’ve tried something like this for the HTML file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Main Page</title>
    <!-- Reference Chart.js from node_modules -->
    <script src="/node_modules/chart.js/dist/chart.umd.js">

With this addition to the app.js server file:

app.use(express.static(path.join(__dirname, '..', 'node_modules')));

However this does not display the chart and instead gives me these errors in the console:

“GET http://localhost:3000/node_modules/chart.js/dist/chart.umd.js net::ERR_ABORTED 404 (Not Found)”
“Refused to execute script from ‘http://localhost:3000/node_modules/chart.js/dist/chart.umd.js’ because its MIME type (‘text/html’) is not executable, and strict MIME type checking is enabled.”
“main:45 Uncaught ReferenceError: Chart is not defined”

I’ve checked the file paths multiple times with console logs and consulting ChatGpt to bugfix to make sure they were correct. Even tried feeding it the absolute path instead of the VScode suggested relative path.

Is there a simple fix to this? or should I just default to the CDNJS reference and give up on trying to use the local packages of Chart.js I downloaded from npm.

Authors Note:
Sorry If I’m not describing things correctly or am misunderstanding certain concepts. I’m relatively new to full-stack web development so take it easy on me lol.

tsc with skipLibCheck still check node_modules

I use cli npx tsc --noEmit --skipLibCheck, it still raise err

node_modules/@types/node/util.d.ts:1631:41 - error TS1005: '(' expected.

1631         keys(): IterableIterator<string>;
                                             ~

node_modules/@types/node/util.d.ts:1646:17 - error TS1005: ',' expected.

1646         set(name: string, value: string): void;
                     ~

node_modules/@types/node/util.d.ts:1646:32 - error TS1005: ',' expected.

1646         set(name: string, value: string): void;
                                    ~

node_modules/@types/node/util.d.ts:1646:41 - error TS1005: ';' expected.

1646         set(name: string, value: string): void;
                                             ~

node_modules/@types/node/util.d.ts:1646:47 - error TS1109: Expression expected.

1646         set(name: string, value: string): void;
                                                   ~

node_modules/@types/node/util.d.ts:1650:17 - error TS1005: ';' expected.

1650         values(): IterableIterator<string>;
                     ~

node_modules/@types/node/util.d.ts:1650:43 - error TS1005: '(' expected.

1650         values(): IterableIterator<string>;
                                               ~

node_modules/@types/node/util.d.ts:1654:26 - error TS1005: ';' expected.

1654         [Symbol.iterator]: typeof MIMEParams.prototype.entries;
                              ~

node_modules/@types/node/util.d.ts:1656:1 - error TS1128: Declaration or statement expected.

1656 }
     ~

Migrating to React 17: Uncaught ReferenceError: React is not defined

After following all the steps mentioned in react website for migrating from react 16 to react 17
After removing react import

I see following error

Uncaught ReferenceError: React is not defined

Babel.config.js

module.exports = function(api) {
  api.cache(true);

  const presets = [
    '@babel/preset-env', 
    ["@babel/preset-react", {"runtime": "automatic"}]
  ];

  const plugins = [
    ['@babel/plugin-proposal-class-properties'],
    '@babel/plugin-syntax-dynamic-import',
    '@babel/plugin-proposal-nullish-coalescing-operator',
    '@babel/plugin-proposal-optional-chaining',
    ["@babel/plugin-transform-react-jsx", {
      "runtime": "automatic"
    }]
  ];

  const env = {
    test: {},
    cucumber: {
      plugins: [
        '@babel/plugin-transform-regenerator',
        [
          '@babel/plugin-transform-runtime',
          {
            regenerator: true,
          },
        ],
      ],
    },
    cypress: {
      plugins: ['istanbul'],
    },
  };

  return {
    presets,
    plugins,
    env,
  };
};

devDependencies

    "@babel/plugin-transform-react-jsx": "7.23.4",
    "@babel/plugin-proposal-class-properties": "^7.5.5",
    "@babel/plugin-proposal-nullish-coalescing-operator": "^7.12.1",
    "@babel/plugin-proposal-optional-chaining": "^7.12.1",
    "@babel/plugin-proposal-private-property-in-object": "^7.21.11",
    "@babel/plugin-syntax-dynamic-import": "^7.8.3",
    "@babel/preset-env": "^7.24.0",
    "@babel/preset-react": "^7.23.3",

React version: 17.0.2

React 16 to 17 migration I used all the steps in:
https://legacy.reactjs.org/blog/2020/09/22/introducing-the-new-jsx-transform.html

JS: How to use ansi escape codes in strict [duplicate]

I’m using Node.js (with "type": "module") and I get this following error: “Octal escape sequences are not allowed in strict mode.”

file:///home/runner/JavaScript/src/ansi.mjs:9
    return "33[" + escape + "m" + text;
             ^^

SyntaxError: Octal escape sequences are not allowed in strict mode.
    at ModuleLoader.moduleStrategy (node:internal/modules/esm/translators:167:18)
    at callTranslator (node:internal/modules/esm/loader:285:14)
    at ModuleLoader.moduleProvider (node:internal/modules/esm/loader:291:30)

Node.js v20.11.1

Here are my files:

index.js

import * as ansi from './src/ansi.mjs';

const str = ansi.c("testtt", 31,1,4);
console.log(str);

src/ansi.mjs

// escape form: 33[XXXm

const color = (text, ...argv) => {
    let escape = "";
    for (let i = 0; i < argv.length; ++i) {
        if (i === 0) escape += argv[i];
        else escape += ";" + argv[i];
    }
    return "33[" + escape + "m" + text;
};


export {
    color as c
};

Is there any way to do escape sequences in strict mode?

Get absolute x,y of a child from the relative x,y of the parent

Note the following structure:

HTML:

<div class="container">
    <div class="wrapper">
        <div class="image">
            <img src="https://picsum.photos/id/237/1000/500">
        </div>
    </div>
</div>

CSS:

body {
    padding: 100px;
    background: aqua;
}

.container {
    position: relative;
    padding: 0 !important;
    touch-action: none;
    -webkit-user-select: none;
    user-select: none;
    width: 400px;
    height: 400px;
    border: 2px solid black;
}

.wrapper {
    position: relative;
    z-index: 1;
    width: 100%;
    height: 100%;
    padding: 0 !important;
    overflow: hidden;
    background-color: black;
}

.image {
    position: relative;
    max-width: none !important;
    max-height: none !important;
    pointer-events: none;
    width: 100%;
    height: 100%;
    transform: translate(var(--translate-x, 0px), var(--translate-y, 0px)) scale(var(--scale, 0));
    --scale: 2;
    --translate-x: 170px;
    --translate-y: -100px;
}

img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    object-position: center;
    background: red;
}

If you prefer, here is the JSFiddle link.

When I click on the parent (.wrapper element) I will get an x,y. Let’s suppose I click on the top right corner (in the example it would be close to the dog’s eye). The value I should get relative to this element is something close to (x: 300, y: 0).

However, if we consider the real image (which has dimensions 1000×500) we know that this click region (the dog’s left eye) corresponds to x:505 and y:205 (approximately).

What I want is precisely that. From the 5 variables:

  • X of the click (relative to parent)
  • Y of the click (relative to parent);
  • CSS attribute –scale;
  • CSS attribute –translate-x;
  • CSS attribute –translate-y;

Get the absolute x, y of the image (considering its real size).

Comments:

The image can be moved within the container. For this I am using the Zoomist plugin. It was the only plugin I found that did this behavior of being able to zoom and move the image within a container of a pre-fixed size.

If there is another solution (another plugin for example) that would be better for my purpose, it would be welcome. Basically it all comes down to being able to zoom and move an image within a region and when clicking on a region (that is part of the image) I get its real x,y.

how to use vueUse/nuxt useSwipe in a v-for loop

I am trying to make a v-for loop list, that lists over my wine bottle. I want to add the ability for each bottle to have its own useSwipe element to which i can swipe over the div to then show a button that can be clicked to remove the bottle from my cellar. Within the list each bottle has a bottleId and i only want one bottle to be swiped at a time, and then if a bottle with a different id is clicked or touched it will close the bottle that is showing the button.

This is the list code, i have tried making the functions and have a basic one working currently but sometimes when another list item is clicked it will remove the bottle without displaying the button.

<div v-for="(bottle, index) in filteredBottles" :key="bottle.bottleId">
  <div>
    {{ bottle.bottle_name }}
  </div>
  <button @click="deleteBottle(bottle.bottleId)">Delete Bottle</button>
</div>

Error while setting up JSON Server Auth: Cannot find module json-server

I followed all the necessary steps to run JSON Server, and it starts running perfectly. However, when I try to set up JSON Server Auth using the command:

json-server-auth -w db.json

I encounter the following error:

C:UsersAhmadDownloadskhalid_donebackend>json-server-auth -w db.json
node:internal/modules/cjs/loader:1147
  throw err;
  ^

Error: Cannot find module 'json-server'
Require stack:
- C:UsersAhmadAppDataRoamingnpmnode_modulesjson-server-authdistguards.js
- C:UsersAhmadAppDataRoamingnpmnode_modulesjson-server-authdistbin.js
    at Module._resolveFilename (node:internal/modules/cjs/loader:1144:15)
    at Module._load (node:internal/modules/cjs/loader:985:27)
    at Module.require (node:internal/modules/cjs/loader:1235:19)
    at require (node:internal/modules/helpers:176:18)
    at Object.<anonymous> (C:UsersAhmadAppDataRoamingnpmnode_modulesjson-server-authdistguards.js:6:20)
    at Module._compile (node:internal/modules/cjs/loader:1376:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1435:10)
    at Module.load (node:internal/modules/cjs/loader:1207:32)
    at Module._load (node:internal/modules/cjs/loader:1023:12)
    at Module.require (node:internal/modules/cjs/loader:1235:19) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [
    'C:\Users\Ahmad\AppData\Roaming\npm\node_modules\json-server-auth\dist\guards.js',
    'C:\Users\Ahmad\AppData\Roaming\npm\node_modules\json-server-auth\dist\bin.js'
  ]
}

Node.js v21.2.0

I followed all the steps properly, including running the following commands:

npm install json-server-auth
npm install json-server
json-server --watch db.json -m ./node_modules/json-server-auth

However, when I run json-server –watch db.json, it starts the localhost on port 3000.

when i run

json-server --watch db.json -m ./node_modules/json-server-auth

it shows error

Unknown option '-m'
Usage: json-server [options] <file>

Options:
 -p, --port <port>  Port (default: 3000)
 -h, --host <host>  Host (default: localhost)
 -s, --static <dir> Static files directory (multiple allowed)
 --help             Show this message
 --version          Show version number

Kindly help me to resolve it and setup auth server.
Thanks in advance!

Flask Session not storing data correctly

Here’s my front-end that’s sending the data:

async function notifyBackendAboutUpload(fileName) {
    try {
        const response = await fetch('http://127.0.0.1:5000/notify-upload', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ fileName }),
            credentials: 'include',
        });

        const responseData = await response.json();
        console.log(responseData);
    } catch (error) {
        console.error('Error notifying the backend:', error);
    }

Here’s my __init__.py:

from flask import Flask, session
from flask_cors import CORS
from dotenv import load_dotenv
import os


def create_app():
    load_dotenv()  # Load environment variables
    app = Flask(__name__)

    # Configuration from environment variables
    app.config["AWS_ACCESS_KEY_ID"] = os.getenv("AWS_ACCESS_KEY_ID")
    app.config["AWS_SECRET_ACCESS_KEY"] = os.getenv("AWS_SECRET_ACCESS_KEY")
    app.config["AWS_REGION"] = os.getenv("AWS_REGION")
    app.config["SECRET_KEY"] = os.getenv("SECRET_KEY")
    app.config["SESSION_COOKIE_SAMESITE"] = "None"
    CORS(app, supports_credentials=True)

    from app.routes.routes import routes as routes_blueprint

    app.register_blueprint(routes_blueprint)

    # Potentially add more blueprint registrations here

    return app

Here’s my routes.py:

from flask import Blueprint, jsonify, request, session, redirect, url_for
from flask_cors import CORS
from app.services.aws_service import fetch_csv_from_s3

routes = Blueprint("routes", __name__)

CORS(routes, supports_credentials=True)

@routes.route("/test-s3-fetch")
def test_s3_fetch():
    bucket_name = "instanalytics"
    object_key = session.get("fileName")
    print('Retrieved from session:', object_key)
    if not object_key:
        return jsonify({'error': 'No file name provided'}), 400
    # df = fetch_csv_from_s3(bucket_name, object_key)
    return jsonify({"message": f"FileName from session: {object_key}"})
    # return jsonify(df.head().to_dict())


@routes.route('/notify-upload', methods=['POST'])
def notify_upload():
    data=request.get_json()
    fileName=data['fileName']
    if not fileName:
        return jsonify({'error': 'Filename is required'}), 400

    session['fileName'] = fileName
    print('Stored in session:', session.get('fileName'))

    return redirect(url_for("routes.test_s3_fetch"))


@routes.route("/test-session")
def test_session():
    # Directly manipulate and check session data
    session["test"] = "Session is working!"
    print("Session data:", session)
    return jsonify({"testSessionValue": session.get("test")})

Now, I’m trying to use the sent file name from the front-end to use here and it’s storing the fileName fine but it’s not retrieving it correctly for some reason. Here’s the logs:

Stored in session: aggregate.csv
127.0.0.1 - - [04/Apr/2024 05:47:18] "POST /notify-upload HTTP/1.1" 302 -
Retrieved from session: None
127.0.0.1 - - [04/Apr/2024 05:47:18] "GET /test-s3-fetch HTTP/1.1" 400 -

I’m new to flask so please let me know what I’m doing wrong. Thanks.

What is the value in Column Primereact

I need to create a function that deletes the product I selected in an expanding line in Primereact.

const actionProdutoBodyTemplate = (rowData: Sistema.DetalhePedidos) => {
    return (
        <>
            <Button icon="pi pi-trash" rounded severity="danger" className="mr-2" onClick={() => deletaProduto(rowData)} />
        </>
    );
};

in my deleteProduto function, I did a console.log(rowData) and the information I need comes (information about the product I selected, such as id, name, etc…)

However, when I add some parameters to the actionProdutoBodyTemplate call, the RowData value changes.

const rowExpansionTemplate = (data: Sistema.Produtos) => {
// Filtrar os detalhes das vendas para mostrar apenas os detalhes da venda atual
const detalhesDaVendaAtual = detalhesDasVendas.filter((detalhe: any) => data.detalhes.includes(detalhe.id));

    return (
        <div className="orders-subtable">
            <h5>Produtos da Venda de Código {data.id}</h5>
            <DataTable emptyMessage="Nenhum Produto na Venda" value={detalhesDaVendaAtual} responsiveLayout="scroll">
                <Column header="Imagem" body={imageBodyTemplate}></Column>
                <Column field="produto.nome" header="Produto" sortable></Column>
                <Column field="quantidade" header="Quantidade" sortable></Column>
                <Column field="produto.custo" header="Custo" sortable></Column>
                <Column field="produto.peso" header="Peso" sortable></Column>
                <Column field="produto.valor" header="Valor" sortable></Column>
                <Column body={actionProdutoBodyTemplate} header="Ações" headerStyle={{ minWidth: '12rem' }}></Column>
            </DataTable>
        </div>
    );
};

What value is passed to actionProdutoBodyTemplate when it has no parameters?

How to fetch and display data from the corresponding column in database in phpMyAdmin

I have been trying to fetch and display the corresponging first name, last name, email, and username (once logged in) to a HTML file and I cant seem to get the information to display. Please help.

//SAA_Register_Connect.php

<?php
    $firstName = $_POST['firstname'];
    $lastName = $_POST['lastname'];
    $email = $_POST['email'];
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Database connection
    $conn = new mysqli('localhost','root','','test');
    if($conn->connect_error){
        echo "$conn->connect_error";
        die("Connection Failed : ". $conn->connect_error);
    } else {
        $stmt = $conn->prepare("INSERT INTO register(firstName, lastName, email, username, password) VALUES (?, ?, ?, ?, ?)");
        $stmt->bind_param("sssss", $firstName, $lastName, $email, $username, $password);
        $execval = $stmt->execute();
        if ($execval === FALSE) {
            echo "Error: " . $conn->error;
        } else {
            echo "Registration successfully...";
        }
        $stmt->close();
        $conn->close();
    }
?>

//SAA_Login_Connect.php

<?php
    $username = $_POST['username'];
    $password = $_POST['password'];

    // Database connection
    $conn = new mysqli('localhost', 'root', '', 'test');
    if ($conn->connect_error) {
        die("Connection Failed: " . $conn->connect_error);
    }

    // Prepare SQL statement to retrieve user data
    $stmt = $conn->prepare("SELECT * FROM register WHERE username = ?");
    $stmt->bind_param("s", $username);
    $stmt->execute();
    $stmt_result = $stmt->get_result();

    if ($stmt_result->num_rows > 0) {
        $data = $stmt_result->fetch_assoc();
        if($data['password'] === $password){
            echo json_encode(array("message" => "Login Successfully",));
        }
        else{
            echo json_encode(array("error" => "Invalid Email or Password"));
        }
    }
    else {
        echo json_encode(array("error" => "Invalid Email or Password"));
    }

    $stmt->close();
    $conn->close();
?>

I tried creating a session in “SAA_Login_Connect.php” to get the fields I wanted and then display them in the html file but I would only recieve errors.

Catching stack-trace in catchAsync function

So I have my server.js like this

//server.js
var express = require('express');
var app = express()

// Error Handler Controller
const globalErrorHandler = require('./controllers/error.controller');

// Import routes
const emailsRoutes = require('./routes/emails.routes')
const notificationsRoutes = require('./routes/notifications.routes')
const reportsRoutes = require('./routes/reports.routes')
const systemRoutes = require('./routes/system.routes')
const siteRoutes = require('./routes/sites.routes')
const accessRoutes = require('./routes/access.routes')
// etc ...

app.use('/v1/emails' ,emailsRoutes)
app.use('/v1/notifications',  notificationsRoutes)
app.use('/v1/reports',  reportsRoutes)
app.use('/v1/system',  systemRoutes)
app.use('/v1/sites',  siteRoutes)
app.use('/v1/access',  accessRoutes)

// Add this AFTER all your routes
app.use(globalErrorHandler);

The structure of the routes files is the next

const emailsRouter = require("express").Router();
const { userValidation } = require("../middleware/Permissions");
const { 
  getEmailGroupsForConfig,
  postEmailGroupsForConfig,
  updateEmailGroupsForConfig
} = require("../controllers/email.controller");

emailsRouter.use(userValidation());

emailsRouter.get("/groups", getEmailGroupsForConfig);
emailsRouter.post("/groups", postEmailGroupsForConfig);
emailsRouter.put("/groups", updateEmailGroupsForConfig);

module.exports = emailsRouter;

My controller files are as follows, each function is exported and independent of all the others

'use strict'
const catchAsync = require("../utils/catchAsync");
const { vmsfull_dbc, replica_dbc } = require("../database_connection");
const AppError = require("../utils/appError");

exports.getEmailGroupsForConfig = catchAsync(async (req, res) => {
  if (!req.user.checkUserPermission('write-email-groups')) {
    return next( new AppError("Unauthorized", 403));
  }
  let sql_query = 'SELECT * from vms_metadata."email_groups" ORDER BY group_name ASC';

  const emailGroupe = await vmsfull_dbc.query(sql_query);

  return res.status(200).send(emailGroupe.rows);
});

Finally, my catch async is the following and it is where I have my question

module.exports = fn => {
  return (req, res, next) => {
    fn(req, res, next).catch(err => {
      // Preservar el stack trace original
      const newError = new Error(err.message);
      newError.statusCode = err.statusCode || 500;
      newError.status = err.status || 'error';
      newError.stack = err.stack; // Preservar el stack trace original

      console.error(newError); // Imprimir el error
      console.trace(error); // Imprimir el stack trace completo

      next(newError);
    });
  };
};

I want to be able to know which middleware or which endpoint had the error, I do detect the error, however when printing console.trace(error);

It only appears from my catchAsync.js file

Trace: [Error]
    at C:MyPathDirectoryserversrcutilscatchAsync.js:22:15
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)

Error Retrieving All Items from Folder in Firebase Storage

Im trying to get all image URLS, in my folder “Taps/”. Everything else in firebase works and is hooked up correctly. Code does not syntax, just catches the error when executed.

Any suggestions?

    const storage = getStorage(app);



  //Retreiving Images
  // Create a reference to the folder containing the images.
  const storageRef = ref(storage, 'Taps/');

  // List all the files in the folder.
  listAll(storageRef).then(async(result) => {
    const {items} = res;
    const urls = await Promise.all(
      items.map((item) => getDownloadURL(item))
    );
    console.log(urls);
  })
  .catch((error) => {
    console.log("Error has occured")
  })

I get:

Error has occured
console.html:780

Why is my Fetch based Vercel API Function Not Working

I was making a Vercel API create domain function (prompts are going to be replaced later)

async function createCustomDomain(vercelToken) {
  alert('Wait');
  var projectID = prompt('Enter the project ID:');
  var domain = prompt(
    "Enter desired domain (will be forced to end with '.vercel.app'):",
  );
  var x = domain.endsWith('.vercel.app');
  if (x !== true) {
    domain = domain + '.vercel.app';
  }

  // Call Vercel API to create domain
  const createDomainResponse = await fetch(
    'https://api.vercel.com/v1/domains',
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${vercelToken}`,
      },
      body: JSON.stringify({
        projectID,
        domain,
      }),
    },
  );

  if (createDomainResponse.ok) {
    console.log(
      `Successfully created domain ${domain} for project ${projectID}`,
    );
    alert(`Successfully created domain ${domain} for project ${projectID}`);
  } else {
    console.error('Failed to create domain:', createDomainResponse.statusText);
    alert('Failed to create domain. Please check the console for details.');
    alert(createDomainResponse.statusText);
  }
}

I was making it make a domain but unfortunately I couldn’t get the service to work or I was stupid does anyone know why the code doesn’t work