global is not defined error when trying to import aws-amplify/storage

node v20.11.1 | git version 2.44.0.windows.1 | npm 10.5.0 | amplify 12.10.1 | aws-cli/2.15.26 Python/3.11.8 Windows/10 exe/AMD64 prompt/off | windows 10

I’ve been having this problem on my main project so I decided to create a new one to test and still get the same problem. I am using quasar framework with vue 3 if that helps.

Whenever I try to use import {} from 'aws-amplify/storage'; I get this error:
ReferenceError: global is not defined at node_modules/@aws-amplify/storage/node_modules/buffer/index.js.

When I use import {} from "aws-amplify/auth"; and import {} from "aws-amplify/api"; they do not give the error and the api queries work as well as the auth.

I’ve followed the amplify documentation to setting up my project.

I looked at node_modules > @aws-amplify > storage > node_modules > buffer > index.js and I’ve found the word global mentioned only twice and it looks like this:

 * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
 * get the Object implementation, which is slower but behaves correctly.
 */
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
  ? global.TYPED_ARRAY_SUPPORT
  : typedArraySupport()

Code of my IndexPage.vue from newly created project:

<template>
  <q-page class="flex flex-center">
    <img
      alt="Quasar logo"
      src="~assets/quasar-logo-vertical.svg"
      style="width: 200px; height: 200px"
    />
  </q-page>
</template>

<script setup>
import { generateClient } from "aws-amplify/api";
import { fetchAuthSession } from "aws-amplify/auth";
import { uploadData } from "aws-amplify/storage";
</script>

My main index.js file found in src > router > index.js:

import { route } from "quasar/wrappers";
import {
  createRouter,
  createMemoryHistory,
  createWebHistory,
  createWebHashHistory,
} from "vue-router";
import routes from "./routes";
import { Amplify } from "aws-amplify";
import amplifyconfig from "src/amplifyconfiguration.json";

Amplify.configure(amplifyconfig);
/*
 * If not building with SSR mode, you can
 * directly export the Router instantiation;
 *
 * The function below can be async too; either use
 * async/await or return a Promise which resolves
 * with the Router instance.
 */

export default route(function (/* { store, ssrContext } */) {
  const createHistory = process.env.SERVER
    ? createMemoryHistory
    : process.env.VUE_ROUTER_MODE === "history"
    ? createWebHistory
    : createWebHashHistory;

  const Router = createRouter({
    scrollBehavior: () => ({ left: 0, top: 0 }),
    routes,

    // Leave this as is and make changes in quasar.conf.js instead!
    // quasar.conf.js -> build -> vueRouterMode
    // quasar.conf.js -> build -> publicPath
    history: createHistory(process.env.VUE_ROUTER_BASE),
  });

  return Router;
});

and my amplifyconfiguration.jsonsrc > amplifyconfiguration.json:

{
  "aws_project_region": "ap-southeast-2",
  "aws_cognito_identity_pool_id": "ap-southeast-2:xxx",
  "aws_cognito_region": "ap-southeast-2",
  "aws_user_pools_id": "ap-southeast-2_xxx",
  "aws_user_pools_web_client_id": "xxx",
  "oauth": {},
  "aws_cognito_username_attributes": [],
  "aws_cognito_social_providers": [],
  "aws_cognito_signup_attributes": [
    "EMAIL"
  ],
  "aws_cognito_mfa_configuration": "OFF",
  "aws_cognito_mfa_types": [
    "SMS"
  ],
  "aws_cognito_password_protection_settings": {
    "passwordPolicyMinLength": 8,
    "passwordPolicyCharacters": []
  },
  "aws_cognito_verification_mechanisms": [
    "EMAIL"
  ],
  "aws_user_files_s3_bucket": "testprojectstorage115825-dev",
  "aws_user_files_s3_bucket_region": "ap-southeast-2",
  "aws_appsync_graphqlEndpoint": "https://xxx.appsync-api.ap-southeast-2.amazonaws.com/graphql",
  "aws_appsync_region": "ap-southeast-2",
  "aws_appsync_authenticationType": "API_KEY",
  "aws_appsync_apiKey": "xxx"
}

How can I fix this Javascript “ui string” error in my randomizer code?

var nbaName = getColumn("stats","NAME"); 
var nbaPPG = getColumn("stats", "PPG");
var nbaPos = getColumn("stats", "POS");
var nbaAge = getColumn("stats", "AGE");

//filteredlists
var filteredNbaName = [];
var filteredNbaPPG = [];
var filteredNbaPOS = [];
var filteredNbaAge = [];
listSetup();
//setting up lits
onEvent("dropdown1", "change", function( ) {
  listSetup();
});
//filterfunction
function filter() {
  
 filteredNbaName = [];
 filteredNbaPPG = [];
 filteredNbaPOS = [];
 filteredNbaAge = [];
}
//loop
var age = getText("dropdown1");
for (var i = 0; i <nbaAge.length; i++) {
  if(nbaAge[i] < 25 && age == "Young"){
    appendItem(filteredNbaName, nbaName[i]);
    appendItem(filteredNbaPPG , nbaPPG[i]);
  } else if( nbaAge[i] > 25 && age == "Old") {
     appendItem(filteredNbaName, nbaName[i]);
     appendItem(filteredNbaPPG , nbaPPG[i]);
     
  }
}
//random
//var randomIndex;
function updateScreen(){
   var randomIndex = randomNumber(0, filteredNbaName.length-1);
    setText("NameOfPlayer", filteredNbaName[randomIndex]);
    //setText("PointsPerGame", filteredNbaPPG[randomIndex]);
   
    
}


function listSetup(){
  filter();
  updateScreen();
}

I expected to get a random player based on my ui. So if the user selects the option “young” the code looks through the data and picks a random NBA player under the age of 25 but instead i get ” ARNING: Line: 40: setText() text parameter value (undefined) is not a uistring.
ERROR: Line: 40: TypeError: Cannot read properties of undefined (reading ‘toString’)”
Please help.

fetch returns some HTML looking stuff rather then the stuff I fetched

so I am very new to web development and after learning the basics I wated to learn a framework so I chose vue and run it with vite
created a project with npm init vue@latest witch setups vue with vite and it works great the big problem for me is I need to acess some JSON file trough fetch but when I use fetch it returns some HTML looking code like this

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="module" src="/@vite/client"></script>

    <meta charset="UTF-8">
    <link rel="icon" href="/favicon.ico">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>My Website</title>
  </head>
  <body>
  <div id="app"></div>
    <script type="module" src="/src/main.js?t=1710967198517"></script>
  </body>
</html>

rather than the actuall JSON file

the code that that I am running is

fetch(path/to/my/file.json).then((p) => p.json())

the thing is p is equal to the HTML code above not the the json string I am tring to fetch

I am not sure why this is but I think because my website is running on a localhost server because web URL’s work fine it can’t just access my local files trough a simple path my theory is I need to somehow bundle static file with vite but can’t find info on how

also don’t tell me to import the file with import because this would help in other contexts but in my I am using a library that takes in a path or a URL and does the fetch so I can’t just import the JSON I have to fetch it

CSS não funciona no vercel

I have a big problem here and I would like to ask for help, I uploaded a website to Vercel because until then the github pages were unable to deploy, but for some reason the CSS in Vercel doesn’t work, does anyone know why? neither css nor anything involving files taken from the directory (images/sounds) other than what is in html.index (the site has two html pages but only the index works)

React useEffect API Call Returning Undefined [duplicate]

I’m trying to make a fetch request to my backend API in React using UseEffect. But my data is undefined. When I console log my res.json(), I get a pending, fulfilled promise, so I think that means I’m on the right track.

However, after that step, it returns undefined.

Here’s my error:

TypeError: Cannot read properties of undefined (reading 'map')

Here is my code. Please help!

import { useState, useEffect } from "react"
// import { useLoaderData } from "react-router-dom"
import ReactPaginate from "react-paginate"
import Record from "../components/Record"
import FieldName from "../components/FieldName"

const Index = (props) => {
    // let data = useLoaderData()

    const[data, setData] = useState([])
    useEffect(() => {
        fetch("https://backendurl.com/data", {
            method: "GET",
            headers: {
                "Content-Type": "application/json",
            }
        }).then((res) => {
            console.log(res.json())
        }).then((data) => {
            setData(data)
        }).catch((error) => console.log(error))
    })

    return <div className="records">
                {data.map((record) =>
                    <Record record={record} key={record.record_id} />
                )}
           </div>
}

export default Index

Is anyone had issues opening gitbash i might have messed up my environment variables, then it won’t allow it to open any idea of what could fix it?

I was able to open gitbash, all of its files and I need it to open but it’s installed properly.
still won’t open I’ve used task manager, a few other ways recommended to see if i could update the program, I have the latest version I messed with my environment variables, so it might be that can someone please help?

task manager, the Winget key command prompt, administrator running the application

Unable to display values of v-data-table row on click event?

I am trying to display the data of a v-data-table row on click in another container outside the v-data-table. I tried expandable rows of v-data-table but that didn’t worked at all so trying this way:

Here is my code:

<template>
  <v-layout>
    <v-row>
      <v-col>
        <h1>Currencies</h1>
        <v-container class="mx-auto pa-6">
          <v-data-table 
            :items="currencies" 
            :headers="headers" 
            dense
            @click:row="handleCurrencyClick"
          >
            <template v-slot:top>
              <v-toolbar flat>
                <v-toolbar-title>Version {{ info.VRSCversion }}</v-toolbar-title>
              </v-toolbar>
            </template>
          </v-data-table>
        </v-container>
      </v-col>
    </v-row>
    <v-row v-if="selectedCurrency">
      <v-col>
        <v-container class="mx-auto pa-6">
          <h2>Selected Currency Info</h2>
          <pre>{{ selectedCurrency.value }}</pre>
        </v-container>
      </v-col>
    </v-row>
  </v-layout>
</template>

<script setup>
import { ref } from 'vue';
import currencyHelpers from '../lib/currencyHelpers';

const info = ref({});
const currencies = ref([]);
const headers = [
  { title: 'Name', value: 'currencydefinition.fullyqualifiedname' },
  { title: 'ID', value: 'currencydefinition.currencyid' },
  { title: 'ID rego fee', value: 'currencydefinition.idregistrationfees' },
  { title: 'ID import fee', value: 'currencydefinition.idimportfees' },
  { title: 'Converter Name', value: 'currencydefinition.gatewayconvertername' },
  { title: 'Proof Protocol', value: 'currencydefinition.proofprotocol' },
  { title: 'Options', value: 'currencydefinition.options' }
];
const selectedCurrency = ref({});

(async () => {
  info.value = await currencyHelpers.getInfo();
  currencies.value = await currencyHelpers.listCurrencies();
})();

const handleCurrencyClick = (currency) => {
  selectedCurrency.value = currency.value;
  console.log(selectedCurrency.value);
};
</script>

<style scoped>
.ovflvdt {
  max-width: 500px;
}
</style>

I want to display the JSON or raw data of the specific row clicked:

How to send error from spring to react js

When i tried to but a false info or sign in with non verified account he gaves me the same error message

POST http://localhost:8020/shop/auth/signin 401 (Unauthorized)
And the alert gave :
An error occurred while logging in.

my controller code :

  @PostMapping("/auth/signin")
public ResponseEntity<?> signin(@RequestBody LoginRequest loginRequest) {
String username = loginRequest.getEmail();
String password = loginRequest.getPassword();

        System.out.println(username +" ----- "+password);
    
        try {
            Authentication authentication = authenticate(username, password);
            SecurityContextHolder.getContext().setAuthentication(authentication);
    
            String token = jwtTokenProvider.generateToken(authentication);
            AuthResponse authResponse = new AuthResponse();
            authResponse.setStatus(true);
            authResponse.setJwt(token);
    
            return ResponseEntity.ok(authResponse);
        } catch (BadCredentialsException e) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(Collections.singletonMap("error", e.getMessage()));
        }
    }
    
    private Authentication authenticate(String username, String password) {
        UserDetails userDetails = customUserDetails.loadUserByUsername(username);
    
        System.out.println("sign in userDetails - "+userDetails);
        boolean isAccountVerified = checkAccountVerification(username);
    
    
        if (userDetails == null) {
            System.out.println("sign in userDetails - null " + userDetails);
            throw new BadCredentialsException("Invalid username or password");
        }
        if (!passwordEncoder.matches(password, userDetails.getPassword())) {
            System.out.println("sign in userDetails - password not match " + userDetails);
            throw new BadCredentialsException("Invalid username or password");
        }
        if (!isAccountVerified) {
            System.out.println("sign in userDetails - not  verified " + userDetails);
            throw new BadCredentialsException("Your Account is not verified. Please check your email.");
        }
        return new UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());
    }

application.properties :

server.error.include-message=always

my react codes :
Action.js :

const loginRequest = () => ({ type: LOGIN_REQUEST });
const loginSuccess = user => ({ type: LOGIN_SUCCESS, payload: user });
const loginFailure = error => ({ type: LOGIN_FAILURE, payload: error });

export const login = userData => async dispatch => {
dispatch(loginRequest());
try {
const response = await axios.post(`${API_BASE_URL}/auth/signin`, userData);
const user = response.data;
if(user.jwt) localStorage.setItem("jwt",user.jwt)
console.log("login ",user)
dispatch(loginSuccess(user));
} catch (error) {
if (error.response && error.response.data && error.response.data.message) {
dispatch(loginFailure(error.response.data.error));
} else {
dispatch(loginFailure("An error occurred while logging in."));
}
}
};

login.jsx :

{auth.error && (   <Alert severity="error" sx={{ width: '100%' }}>     {auth.error}   </Alert> )}

find the problem or fixing the error

How to solve Web Sockets error crashing Vue app

I have a problem with my Vue app where I cannot get a page to load due to the app crashing. This is the error that shows in the console. I am not really sure why this error is happening because there is no implementation of Web Sockets currently on the app.

I have also added this to the webpack config but it has not resloved ths problem.

const path = require('path');

module.exports = {
  entry: './src/index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'
  },
  devServer: {
    // other devServer options
    webSocketServer: 'none'
  }
  
};

This is the main part of the error.

events.js:173
      throw er; // Unhandled 'error' event
      ^

RangeError: Invalid WebSocket frame: RSV1 must be clear

If anyone has any ideas where this error might be coming from I’d really appreciate the help.

EDIT
I am able to run the app and receive the following in the console:

 App running at:
  - Local:   http://localhost:8080/ 
  - Network: http://192.168.0.147:8080/

  Note that the development build is not optimized.
  To create a production build, run npm run build.

The web socket error appears when I try to navigate to another view.

When exactly is the setTimeout callback put on the macrotask queue?

At which point during the JavaScript event loop does it figure out that a timer has reached its target time and needs to be placed on the macroQueue? Does it do this check after completing each macroQueue/microQueue task, or after the whole batch of macroQueue/microQueue tasks? The event loop has a certain order it runs these tasks and I’m wondering where exactly in this process that the callback is actually added to the macroQueue; I’m not asking when the callback itself gets processed. How exactly does the webapi get that callback into that queue within the event loop order of execution.

Conditionally Render Image on Server in Next.js

I feel like I already know the answer to this, but just wanted to see if anyone had a solution for this.

I have a hero banner where I have one image I want to show on mobile, but there’s another I want to show on desktop.

Usually I would just conditionally render it, but then I get that weird flicker where the image first loads something by default and then switches to the right one.

Is there another way to deal with this?

Thank you!

Promise Fulfilled But Still Pending

I’m writing a function that sends a POST request to my backend API and returns the response as data. I need to use a POST request because I need to send information to the backend. I’m using async/await syntax.

When I console log the data inside the function definition, it clearly shows a resolved promise because the data is logged as an array.

(491) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, …]

However, when I actually call the function, it returns a promise that is fulfilled, with the results (!!), but still pending.

Promise {<pending>}
    [[PromiseState]]: "fulfilled"
    [[PromiseResult]]: Array(491)

I also can’t use “await” outside of the function definition so that doesn’t work. I’ve also tried using .then() after the function call but it doesn’t work either.

Here’s my code. Please help!

import { useState, useEffect } from "react"
// import { useLoaderData } from "react-router-dom"
import ReactPaginate from "react-paginate"
import Record from "../components/Record"
import FieldName from "../components/FieldName"

const Index = (props) => {
    // let data = useLoaderData()

    const fetchRecords = async (currentPage) => {
        const response = await fetch("https://medwallet-backend.onrender.com/data", {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
            },
            body: JSON.stringify({
                currentPage: currentPage
            })
        })

        const data = await response.json()
        return await data
    }

    const [currentPage, setCurrentPage] = useState(1)

    const data = fetchRecords(currentPage).then((data) => {return data})

    const recordsPerPage = 10
    const lastIndex = currentPage * recordsPerPage
    const firstIndex = lastIndex - recordsPerPage
    const records = data.slice(firstIndex, lastIndex)
    const numPages = Math.ceil(data.length / recordsPerPage)

    const handlePageClick = (e) => {
        const page_number = e.selected + 1
        setCurrentPage(page_number)
    }
 
    return <div className="index-container">
            <div className="field-names">
                {fieldNames.map((fieldName) => 
                    <FieldName fieldName={fieldName} key={fieldName} />
                )}
            </div>

            <div className="records">
                {records.map((record) => 
                    <Record record={record} key={record.record_id}/>
                 )}
            </div>

            <ReactPaginate
                previousLabel={"Prev"}
                nextLabel={"Next"}
                breakLabel={"..."}
                pageCount={numPages}
                marginPagesDisplayed={2}
                pageRangeDisplayed={3}
                onPageChange={handlePageClick}
                containerClassName={"pagination justify-content-center"}
                pageClassName={"page-item"}
                pageLinkClassName={"page-link"}
                previousClassName={"page-item"}
                previousLinkClassName={"page-link"}
                nextClassName={"page-item"}
                nextLinkClassName={"page-link"}
                breakClassName={"page-item"}
                breakLinkClassName={"page-link"}
                activeClassName={"active"}
            />

    </div>
}

export default Index```

How to simulate spacebar click multiple times

I want to simulate a spacebar click on the web. I have a react native app where when i press a button it sends a post request to the server. There i want every time a request comes(the button is pressed) a spacebar click to be simulated on the web.
Here is my server code

const express = require('express');
const app = express();
const http = require('http').Server(app);
const io = require('socket.io')(http); // Import and initialize Socket.IO
 
const path = require('path');
const simulateBoost = require('./boost-simulation');
 
const PORT = process.env.PORT || 8080;
 
app.use(express.urlencoded());
app.use(express.json());
 
// Serve static files from the 'public' directory
app.use(express.static(path.join(__dirname, 'public')));
 
// Serve static files from the 'build' directory (Unity WebGL)
app.use(express.static(path.join(__dirname, 'build')));
 
// Route handler for the root URL ("/")
app.get('/', (req, res) => {
    res.sendFile(path.join(__dirname, 'public', 'index.html'));
    
});
 
app.post('/', (req, res) => {
    // Handle the POST request data
    const postData = req.body.data;
    // Process the data as needed
    console.log('Received POST data:', postData);
 
    // Send a response
    res.json({ message: 'Data received successfully' });
 
    if(postData === 'boost') {
        // Sending a message to the frontend to trigger space key press
        io.emit('boost'); // Emitting 'boost' event to all connected clients
        
    }
});
 
// Socket.IO connection handler
io.on('connection', (socket) => {
    console.log('A user connected');
    socket.on('disconnect', () => {
        console.log('User disconnected');
    });
});
 
// Start the server
http.listen(PORT, () => {
    console.log(`Server is running on port ${PORT}`);
});

and here is my script in the html

<!DOCTYPE html>
<html lang="en-us">
<head>
    <meta charset="utf-8">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Unity WebGL Player | Cannon_Game#1</title>
    <link rel="shortcut icon" href="TemplateData/favicon.ico">
    <link rel="stylesheet" href="TemplateData/style.css">
    <script src="game.js" type="module"></script>
</head>
<body>
<div id="unity-container" class="unity-desktop">
    <canvas id="unity-canvas" width=960 height=600 tabindex="-1"></canvas>
    <div id="unity-loading-bar">
        <div id="unity-logo"></div>
        <div id="unity-progress-bar-empty">
            <div id="unity-progress-bar-full"></div>
        </div>
    </div>
    <div id="unity-warning"> </div>
    <div id="unity-footer">
        <div id="unity-webgl-logo"></div>
        <div id="unity-fullscreen-button"></div>
        <div id="unity-build-title">Cannon_Game#1</div>
    </div>
</div>
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/4.2.0/socket.io.js"></script>
<script>
    const socket = io('http://localhost:8080');

    function boostHandler() {
        
        console.log("BOOSTED!");
        window.dispatchEvent(new KeyboardEvent('keydown', {
            key: ' ',
            code: 'Space',
            keyCode: 32,
            which: 32,
            bubbles: false
        }));
        console.log("boosted succefully");
    }
    
    socket.on('boost', boostHandler);
</script>
</body>
</html>

Currently the spacebar is simulated only once and does not work with more than one request

POST http://localhost:3000/serverSide 401 (Unauthorized) Error

I’m trying to send a username and password from an HTML file to a Javascript file that queries an employee table for that username and password. My problem is that the username and password are set to undefined when they are in my serverSide.js file so a proper query is never taking place. In my console window in chrome I’m getting the error POST http://localhost:3000/serverSide 401 (Unauthorized) Error. Attached below is my code

employee-login.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Employee Login - Brookings Activity Center</title>
    <link rel="stylesheet" href="styling.css">
</head>
<body>

    <header>
        <h1>Brookings Activity Center</h1>
    </header>

    <nav>
        <a href="index.html">Home</a>
        <a href="employee-login.html">Employee Login</a>
        <a href="book-event.html">Book an Event</a>
    </nav>

    <section>
        <h2>Employee Login</h2>
        <form id="loginForm" action = "/serverSide" method = "POST">
            <input id = "username" type="text" placeholder="Username" required>
            <br>
            <input id = "password" type="password" placeholder="Password" required>
            <br>
            <button type="button" id = "loginButton">Login</button>
        </form>
        <!-- Not implemented, prototype.-->
        <a href="#forgot-password.html">Forgot password?</a>
    </section>
    <script>
        document.getElementById('loginButton').addEventListener('click', (event) => {
            event.preventDefault(); // Prevent form submission (default behavior)
            
            // Username and password being passed
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
    
            // Send login request to server
            fetch('http://localhost:3000/serverSide', {
            method: 'POST',
            headers: {
                Accept: 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({ username, password }),
        })
            .then(response => {
                if (response.status === 200) {
                    // Username and password match, redirect to employee homepage
                   // window.location.href = 'employeeHomepage.html';
                   alert('Username or Password matches');
                } else {
                    // Username or password is incorrect, display error message
                    alert('Username or Password is incorrect');
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('An error occurred. Please try again later.');
            });
        });
    </script>

    <footer>
        &copy; Brookings Activity Center
    </footer>

</body>
</html>

serverSide.js

const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const { Client } = require('pg');

const app = express();
const port = 3000;

// Enable CORS for all routes
 app.use(cors());

// Middleware to parse request body
app.use(bodyParser.urlencoded({ extended: true }));

// Database connection configuration
const dbConfig = {
  user: 'postgres',
  password: '1234',
  host: 'localhost',
  port: 5432,
  database: 'BAC_DB',
};

// Create a new PostgreSQL client
const client = new Client(dbConfig);

// Connect to the database
client.connect()
  .then(() => {
    console.log('Connected to PostgreSQL database');

    // Define route for employee login
    app.post('/serverSide', (req, res) => {
      const { username, password } = req.body;
      console.log('Received username:', username);
      console.log('Received password:', password);

      // Check the database for the provided username and password
      client.query('SELECT * FROM employee WHERE username = $1 AND password = $2', [username, password], (err, result) => {
        if (err) {
          console.error('Error executing query', err);
          res.status(500).send('Internal Server Error');
        } else {
          if (result.rows.length > 0) {
            // Username and password match, send success response
            res.status(200).json({ success: true });
           // res.status(401).json({ success: false, message: 'Username or Password is incorrect -- server side' });
          } else {
            // Username or password is incorrect, send error response
            res.status(401).json({ success: false, message: 'Username or Password is incorrect -- server side' });
            // res.status(200).json({ success: true });
          }
        }
      }); 
         // For now, let's just send a response back to the client
        // res.send('Received login request');
    }); 

    // Start the server
    app.listen(port, () => {
      console.log(`Server is running on http://localhost:${port}`);
    });
  })
  .catch((err) => {
    console.error('Error connecting to PostgreSQL database', err);
  });

I tried debugging by checking what the username and password is when being sent to serverSide.js by using console.log. Both the username and password show up as undefined so for some reason the username and password are not being sent over properly.