Javascript Express App with MongoDB and Authorization: My details and index view fails to load with the error that [value] is not defined

app.js

const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const { render } = require('ejs');
const courseRoutes = require('./routes/courseRoutes');
const authRoutes = require('./routes/authRoutes');
const cookieParser = require('cookie-parser');
const { requireAuth, checkUser } = require('./middleware/authMiddleware');
const Course = require('./models/course');
const User = require('./models/User');

// express app
const app = express();

// connect to mongodb
const dbURI = 'mongodb+srv://sperry53:[email protected]/?retryWrites=true&w=majority&appName=FinalProjectGroup5';
mongoose.connect(dbURI)
    .then((result) => app.listen(3000))
    .catch((err) => console.log(err));

// register view engine
app.set('view engine', 'ejs');

// middleware and static files
app.use(express.static('public'));
app.use(express.urlencoded({ extended: true }));
app.use(morgan('dev'));
app.use((req, res, next) => {
    res.locals.path = req.path;
    next();
});
app.use(express.json());
app.use(cookieParser());
// app.use(checkUser);

// routes
app.get('*', checkUser);
app.get('/', (req, res) => {
    res.render('index', { title: 'Home' });
    // res.redirect('/courses');
});
app.get('/courses', requireAuth, (req, res) => {
    res.render('courses', { title: 'All Courses' });
});

// course routes
app.use('/courses', requireAuth, courseRoutes);

// auth routes
app.use(authRoutes);


// 404 page
app.use((req, res) => {
    res.status(404).render('404', { title: '404'});
})

courseController.js

const Course = require('../models/course');

const course_index = (req, res) => {
  Course.find().sort({ createdAt: -1 })
    .then(result => {
      console.log('Courses:', courses);
      res.render('courses', { courses: result, title: 'All courses' });
    })
    .catch(err => {
      console.log(err);
    });
}

const course_details = (req, res) => {
  const id = req.params.id;
  Course.findById(id)
    .then(result => {
      res.render('details', { course: result, title: 'Course Details' });
    })
    .catch(err => {
      res.status(404).render('404', { title: 'Course not found' });
    });
}

const course_create_get = (req, res) => {
  res.render('create', { title: 'Create a new course' });
}

const course_create_post = (req, res) => {
  const course = new Course(req.body);
  course.save()
    .then(result => {
      res.redirect('/courses');
    })
    .catch(err => {
      console.log(err);
    });
}

const course_delete = (req, res) => {
  const id = req.params.id;
  Course.findByIdAndDelete(id)
    .then(result => {
      res.json({ redirect: '/courses' });
    })
    .catch(err => {
      console.log(err);
    });
}

module.exports = {
  course_index, 
  course_details, 
  course_create_get, 
  course_create_post, 
  course_delete
}

Things were working properly and then I added too much code without testing each addition because my other views were functioning properly. This is the specific error:

ReferenceError: C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwoviewscourses.ejs:11
9|

All Courses

10| 

11| <% if (courses.length > 0) { %>

12|             <% courses.forEach(course => { %>

13| 

14|             <a class="single" href="/courses/<%= course._id %>">

courses is not defined
at eval (eval at compile (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesejslibejs.js:673:12), :18:8)
at courses (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesejslibejs.js:703:17)
at tryHandleCache (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesejslibejs.js:274:36)
at exports.renderFile [as engine] (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesejslibejs.js:491:10)
at View.render (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesexpresslibview.js:135:8)
at tryRender (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesexpresslibapplication.js:657:10)
at Function.render (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesexpresslibapplication.js:609:3)
at ServerResponse.render (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesexpresslibresponse.js:1039:7)
at C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwoapp.js:43:9
at Layer.handle [as handle_request] (C:UserssnperOneDriveDesktopSDEV 255SDEV_255_Final_Project_Group5_TakeTwonode_modulesexpresslibrouterlayer.js:95:5)

Prettier automatically adds {” “}

When I try to formatting the below code with Prettier:

export default function App() {
  return (
    <View className="h-full flex flex-row justify-center bg-blue-500">
<View className="h-fit">
        <Text className="bg-red-500">THIS WILL BE CENTERED</Text>
  
</View>      <StatusBar style="auto" />
    </View>
  );
}

It becomes:

export default function App() {
  return (
    <View className="h-full flex flex-row justify-center bg-blue-500">
      <View className="h-fit">
        <Text className="bg-red-500">THIS WILL BE CENTERED</Text>
      </View>{" "}
      <StatusBar style="auto" />
    </View>
  );
}

Please note that Prettier automatically adds {" "} between the View and StatusBar tag. I don’t want this behaviour to ever occur. How do I fix it?

Want to stop Prettier from writing {” “}

How to run meta pixel from external js

I want to run meta pixel from external js file with:

<script async src="/includes/js/meta.js"></script>

I have js file like this now:

!function(f,b,e,v,n,t,s)
{if(f.fbq)return;n=f.fbq=function(){n.callMethod?
n.callMethod.apply(n,arguments):n.queue.push(arguments)};
if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
n.queue=[];t=b.createElement(e);t.async=!0;
t.src=v;s=b.getElementsByTagName(e)[0];
s.parentNode.insertBefore(t,s)}(window,document,'script',
'https://connect.facebook.net/en_US/fbevents.js');
fbq('init', '123456789');
fbq('track', 'ViewContent', {
  content_ids: ['123'], // 'REQUIRED': array of product IDs
  content_type: 'product', // RECOMMENDED: Either product or product_group based on the content_ids or contents being passed.
});

What to add in js that script will run?

I try many options and don’t work…

Dynamically load environment variable in NextJs app

I have this NextJs 14.1.3 (app router) application and I want to access the environment variables dynamically in client components at run time. I don’t want to use NEXT_PUBLIC prefix because they are replaced with the actual value at build time. Instead I want to load them dynamically (at run time). For example consider this variable which is defined in any .env* files at the root of the project:

MAIN_API_URL=https://example.com

Once the project is build and started (using npm run build and npm run start), I want to be able to change the value of this variable and use the updated value in my client components (after stopping the project and starting it again without rebuilding). This is possible in server components. Is it possible to do this in client components?

Angular Guard: Checking HTTP-Only Cookie Auth on Server- CanActivateFn

I have a HTTP only cookie Auth Method;
server:

export const checkCookie = async (req: Request, res: Response) => {
  const token = req.cookies["token"];
  if (!token) {
    return res.status(401).json({ message: "Unauthorized" });
  }
  try {
    const decoded = jwt.verify(token, JWT_SECRET);
    res.status(200).json({ success: true, userId: decoded.id });
  } catch (error) {
    res.status(401).json({ message: "Unauthorized" });
  }
};

the route for this API call is:
GET localhost:8000/api/v1/login

and router guard in Angular:

import { CanActivateFn } from '@angular/router';
import axios from 'axios';

export const loginAuthGuard: CanActivateFn = (route, state) => {
  return true;
};

How to send a request from this quard to this endpoint to check this Http only cookin using CanActivateFn that is modern and automaticly generated?

Creating Infinite horizontall scrolling ( like Ring )

I am trying to make a container that has children Horizontally and moves from left to right
Each of those children , when it reach the end of the container => goes to the start of the container
let’s imagine that it contain 4 children:
0% : ..1 | 2 | 3 | 4 ..
25% : ..4 | 1 | 2 | 3..
50% : ..3 | 4 | 1 | 2..
75% : ..2 | 3 | 4 | 1..
100% : ..1 | 2 | 3 | 4..
not like the carousel, but like the ring rolling (smooth )
for infinite time

here is the code I have tried:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>HI</title>
    <style>
        .container {
            height: 200px;
            width: 800px;
            border: 1px solid #333;
            overflow: hidden;
            margin: 25px auto;
            }

        .box{
            background: orange;
            height: 180px;
            margin:10px;
            animation-name: move;
            animation-duration: 10s;
            animation-iteration-count: infinite;
            animation-direction: right;
            animation-timing-function: linear;
            display: flex;
        }
        .card {
            background: #fff;
            height: 150px;
            min-width: 100px;
            margin: 15px;
            border-radius: 10px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }
        .box:hover {
            animation-play-state: paused;
        }
        @keyframes move {
            0% {
                margin-left: 000px;
            }
            25% {
                margin-left: 100px;
            }
            50% {
                margin-left: 200px;
            }
            75% {
                margin-left: 300px;
            }

            100% {
                margin-left: 400px;
            }
        }
    </style>
</head>

<body>
    <div class="container">
        <div class="box">
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
            <div class="card"></div>
        </div>
    </div>
    <script></script>
</body>
</html>

may use JavaScript , Bootstrap, tailwind CSS.

React, using “useFetch” is not working when parameter is passed

I was using a basic useFecth for a GET request from my JSON server file. I was working well. But later I wanted add extra functionality and make it work for POST and for another API too. The thing its still working with my json file, but doesnt work with the API. (btw the API is using FormData, thats why im sending as FormData. But when I run calendar page it seems like “useFetch” in there is not even running)

This is my App.js:

import './App.css';
import {BrowserRouter as Router, Routes, Route} from 'react-router-dom';
import Home from './Pages/Home';
import About from './Pages/About';
import NavBottom from './Components/NavBottom';
import NavTop from './Components/NavTop';
import useFetch from './Components/useFetch';
import Admission from './Pages/Admission';
import Calendar from './Pages/Calendar';

function App() {
  const {data: user, error, isPending} = useFetch('http://localhost:8000/users/1');
  const {data: apiData, error: apiError, isPending: apiIsPending} = useFetch('http://localhost:8000/apiData/1');


  return (
    <div className="App">
      {error && <div>{error}</div>}
      {isPending && <div>Loading...</div>}
      {user && (
        <div>
          <Router>
            <nav>
                <NavTop user={user} />
                <NavBottom />
            </nav>

            <div className="content">
              <Routes>
                <Route path="/" element={<Home user={user}/>} />
                <Route path="/calendar" element={<Calendar user={user} apiData={apiData}/>} />
                <Route path="/about" element={<About />} />
                <Route path="/admission" element={<Admission />} />
              </Routes>
            </div>
          </Router>
        </div>
      )}
    </div>
  );
}

export default App;

This is the calendar page Calendar.js

import React from 'react'
import useFetch from '../Components/CalendarFetch'
import { useState } from 'react';

const Calendar =  ({user, apiData}) => {

    const apiFormData = new FormData();
    apiFormData.append('school_group', apiData.schoolGroup);
    apiFormData.append('db', apiData.db);
    apiFormData.append('student_idx', user.calendarId);

    
    const {data: calendar, error: calError, isPending: calIsPending} = useFetch('https://MY-API-LINK', apiFormData);

  return (
    <div>
        {calError && <div>{calError}</div>}
        {calIsPending && <div>Loading...</div>}
        {calendar && 
        
        <div>
            <h2>Calendar</h2>
            {console.log(calendar)}
        </div>
        }
    </div>
  )
}

export default Calendar

and this is my useFetch.js

import { useState, useEffect } from 'react';

const useFetch = (url, formData = null) => {
    const [data, setData] = useState(null);
    const [isPending, setIsPending] = useState(true);
    const [error, setError] = useState(null);

    useEffect(() => {
        console.log(url)

        const abortCont = new AbortController();

        const fetchData = async () => {
            try {
                const fetchOptions = {
                    method: 'GET',
                    signal: abortCont.signal,
                };


                if (formData) {
                    fetchOptions.method = 'POST';
                    fetchOptions.body = formData;
                }

                const response = await fetch(url, fetchOptions);

                if (!response.ok) {
                    throw Error('Could not fetch the data for that resource!');
                }

                const responseData = await response.json();
                setData(responseData);
                setIsPending(false);
                setError(null);
            } catch (err) {
                if (err.name === 'AbortError') {
                    console.log('Fetch aborted');
                } else {
                    setIsPending(false);
                    setError(err.message);
                }
            }
        };

        fetchData();

        return () => abortCont.abort();
    }, [url, formData]);

    return { data, isPending, error };
};

export default useFetch;

I tried to to just pass it into the useFetch in calendar. but it returns fetch aborted

Docker – how to prevent a file being override when using volume?

First of all, I have a dockerized application, which is consisted of 3 containers (web, backend, database).

folder structure

- backend
   ...
   - package.json
   - Dockerfile
- web
   ...
   - package.json
   - Dockerfile

- docker-compose.yml

This is docker-compose.yml

version: '3.5'

services:
  web:
    build:
      context: ./web
      dockerfile: Dockerfile
    container_name: web
    ports:
      - '3000:3000'
    volumes:
      - ./web:/app
      - /app/.next
    depends_on:
      - backend

  backend:
    container_name: backend
    ...
    depends_on:
      - database

  database:
    container_name: mongodb
    ...

web/Dockerfile – which is copied from nextJS official examples

FROM node:18-alpine AS base

# Install dependencies only when needed
FROM base AS deps
# Check https://github.com/nodejs/docker-node/tree/b4117f9333da4138b03a546ec926ef50a31506c3#nodealpine to understand why libc6-compat might be needed.
RUN apk add --no-cache libc6-compat
WORKDIR /app

# Install dependencies based on the preferred package manager
COPY package.json yarn.lock* package-lock.json* pnpm-lock.yaml* ./
RUN 
  if [ -f yarn.lock ]; then yarn --frozen-lockfile; 
  elif [ -f package-lock.json ]; then npm ci; 
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm i --frozen-lockfile; 
  else echo "Lockfile not found." && exit 1; 
  fi


# Rebuild the source code only when needed
FROM base AS builder
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY . .

# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Uncomment the following line in case you want to disable telemetry during the build.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN 
  if [ -f yarn.lock ]; then yarn run build; 
  elif [ -f package-lock.json ]; then npm run build; 
  elif [ -f pnpm-lock.yaml ]; then corepack enable pnpm && pnpm run build; 
  else echo "Lockfile not found." && exit 1; 
  fi

# Production image, copy all the files and run next
FROM base AS runner
WORKDIR /app

ENV NODE_ENV production
# Uncomment the following line in case you want to disable telemetry during runtime.
# ENV NEXT_TELEMETRY_DISABLED 1

RUN addgroup --system --gid 1001 nodejs
RUN adduser --system --uid 1001 nextjs

COPY --from=builder /app/public ./public

# Set the correct permission for prerender cache
RUN mkdir .next
RUN chown nextjs:nodejs .next

# Automatically leverage output traces to reduce image size
# https://nextjs.org/docs/advanced-features/output-file-tracing
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static

USER nextjs

EXPOSE 3000

ENV PORT 3000
# set hostname to localhost
ENV HOSTNAME "0.0.0.0"

# server.js is created by next build from the standalone output
# https://nextjs.org/docs/pages/api-reference/next-config-js/output
CMD ["node", "server.js"]

Problem
After running docker-compose up -d, an error occurs in the web container.

Error: Cannot find module '/app/server.js'
    at Module._resolveFilename (node:internal/modules/cjs/loader:1134:15)
    at Module._load (node:internal/modules/cjs/loader:975:27)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:128:12)
    at node:internal/main/run_main_module:28:49 {
  code: 'MODULE_NOT_FOUND',
  requireStack: []
}

Then I realized that the volume in web override the server.js

services:
  web:
    build:
      context: ./web
      dockerfile: Dockerfile
    container_name: web
    ...
    volumes:
      - ./web:/app // The error is because of this line
      ...
    depends_on:
      - backend

All right, so after I remove

volumes:
      - ./web:/app

, web container works fine now, but live reloading doesn’t work now.
I have to re-build my docker image to see the changes after I modify the code.

So now my question is, is it possible to keep server.js in my docker container, while still having the live reloading functionality?

Why is this class object displaying incorrect data in the console?

I’m simply creating an object using a class but the console displays the value of currentNote as 6 instead of 0. I’m using NextJS and Chrome.

    class TrackInfo extends Midi {
        constructor(currentNote, type, channel, delta, deltaInMS, number, velocity, instrument, trackLength, midiFormat, midiNumOfTracks, midiTicksPerBeat, microSecondsPerBeat) {
            super(midiFormat, midiNumOfTracks, midiTicksPerBeat);
            this.currentNote = currentNote;
            this.type = type;
            this.channel = channel;
            this.delta = delta;
            this.deltaInMS = deltaInMS;
            this.number = number;
            this.velocity = velocity;
            this.instrument = instrument;
            this.trackLength = trackLength;
            this.microSecondsPerBeat = microSecondsPerBeat;
        }
    }
    let track;

    const initialTrackLoad = () => {

        track = new TrackInfo(
            0,
            trackInfo[0].type,
            trackInfo[1].channel,
            trackInfo[0].deltaTime,
            trackInfo[0].deltaTime * (1000.0 * (60.0 / ((60000000 / microsecondsPerBeat) * headerInfo.ticksPerBeat))),
            trackInfo[0].noteNumber,
            trackInfo[0].velocity,
            trackInfo[0].text,
            trackInfo.length,
            headerInfo.format,
            headerInfo.numTracks,
            headerInfo.ticksPerBeat,
            microsecondsPerBeat,
        );
        console.log("TRACK AFTER INIT = ", track)
        console.log("CURRENT NOTE AFTER INIT = ", track.currentNote)
    }

Console shows (currentNote: 6) in console even though the next console log confirms its actually 0, it even shows (currentNote: 0) literally in the object preview right above the drop down.

Console log results

However when I create the object outside of this file it seems to work fine.
What is happening here?

I’ve tried restarting the server and visual code.

Midi class also if it’s relevant at all:

    class Midi {
        constructor(format, numOfTracks, ticksPerBeat) {
            this.format = format;
            this.numOfTracks = numOfTracks;
            this.ticksPerBeat = ticksPerBeat;
        }
    }

Unable to sign in with redirect with firebase on mobile

In my application I am trying to sign in with google redirect. My redirect login works on my chrome browser but my safari browser does not work.

Here is some code that I have that works on chrome

  try {
      const result = await getRedirectResult(auth);
    } catch (err) {
      if (err.code === 'auth/credential-already-in-use') {
        const cred = GoogleAuthProvider.credentialFromError(err);
        signInWithCredential(auth, cred);
      }
    }

In the above snippet, I see that result would contain the auth credential object. In safari, the auth credential is null. I’ve checked the documentation here https://firebase.google.com/docs/auth/web/redirect-best-practices#signinwithpopup but I’m working with localhost and it’s failing.

I found in this documenation https://firebase.google.com/docs/reference/js/v8/firebase.auth.Auth#getredirectresult that If no redirect operation was called, returns null. So in this case, my guess is that the redirect operation was not called on my browser. What gives?

Which method is more effective: utilizing window.showSaveFilePicker or generating a data URL and downloading a file using an anchor element?

I was developing a feature that enables the user to download a PNG and a JSON. After conducting research, I utilized the window.showSaveFilePicker method to facilitate the download of the JSON file. For the PNG file, I generated a data URL and linked it to the href attribute of an anchor element. By triggering a click event, I successfully enabled the download of the PNG file. This approach was deemed more suitable for the PNG file as it originated from a canvas element, allowing for easy conversion using canvas.toDataURL("image/PNG"). Implementing both ways made me begin to consider whether one method is more effective than the other for downloading files.

The code for both downloads is provided below:

  • JSON:
async function saveJSON() {
    const blob = new Blob([
        JSON.stringify({
            /* object here */
        }, null, 2)
    ], {
        type: "application/json"
    });

    const newHandle = await window.showSaveFilePicker({
        types: [{
            description: "Some description",
            accept: {
                "application/json": [ "application/json" ]
            },
        }],
        id: "save-json-file-picker",
        excludeAcceptAllOption: true,
    });

    const writableStream = await newHandle.createWritable();
    await writableStream.write(blob);
    await writableStream.close();
}
  • PNG:
function savePNG() {
    const canvas = document.createElement("canvas");
    // Logic to create the image in the canvas element goes here
    const url = canvas.toDataURL("image/png");
    const a = document.createElement('a')
    a.href = url;
    a.download = 'image.png';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
}

Both approaches work as expected.

Electron App: How to post electron app HTML form fields to the corresponding postgreSQL table columns

I am making an electron app. I created a table on pgadmin4 called “test”. I want to submit the form “test” on my app’s interface – for each corresponding field (TestLastName, TestFirstName, TestMRN, TestDateOfBirth), I want it to be added to each corresponding column on my “test” table in pgadmin4.
The front-end of the form works, but I think the connection is not really connecting. Thus, the adding to the table in pgadmin4 isn’t working.
I came up with this code after digging around but it’s still not working.
What could be the issue?

This is my “wf_Main.js”

/* --------------- IMPORT NODE.JS --------------- */ 
const { app, BrowserWindow} = require('electron');
const path = require('node:path')
const url = require('url');


// Require electron-reload for live-reloading
if (process.env.NODE_ENV === 'development') {
  require('electron-reload')(__dirname, {
    electron: require('electron'),
  });
}


/* --------------- VARIABLES --------------- */ 
let mainWindow;
let widthVariable = 800;
let heightVariable = 600;




/* --------------- FUNCTIONS --------------- */ 
// Function 1: Open Login Page
function openLoginPage() {
  // Create the browser window
  mainWindow = new BrowserWindow({ 
    width: widthVariable, 
    height: heightVariable, 
    webPreferences: {
      nodeIntegration: true, // This allows button navigation.
      preload:path.join(__dirname, 'wf_Preload.js')
    }, 
  });

  // Load the initial HTML page
  mainWindow.loadFile('wf_Index.html');

  // Listen for the window being closed. Then set window to be nothing:
  mainWindow.on('closed', function () {
    mainWindow = null;
  });
}


// Create the main window when the app is ready. In Electron, app's "ready" event must fire to open browser.:
app.whenReady().then(openLoginPage);


// Quit the app when all windows are closed, except on macOS (Darwin means macOS):
app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit();
});


// Create a new window when the app is activated, except on macOS
app.on('activate', function () {
  if (mainWindow === null) openLoginPage();
});

While my launch html is wf_Index.html, I have a “Login” button that takes me to wf_App.html

This is form in my “wf_App.html”

                        <!---ADD NEW CLIENT:-->
                        <div class="FormBox Test">
                            <form id="form-test" action="/" method="POST">
                                <!---Last Name:-->
                                <div class="FormItem InputBox">
                                    <input type="text" placeholder="Last Name" required id="form-postgreSQL-test-lastNameInput" required name="TestLastName">
                                    <span class="Form ErrorMessage" id="form-postgreSQL-test-lastNameError"></span><br>
                                </div>

                                <!---First Name:-->
                                <div class="FormItem InputBox">
                                    <input type="text" placeholder="First Name" required id="form-postgreSQL-test-firstNameInput" required name="TestFirstName">
                                    <span class="Form ErrorMessage" id="form-postgreSQL-test-firstNameError"></span><br>
                                </div>

                                <!---MRN:-->
                                <div class="FormItem InputBox">
                                    <input type="number" placeholder="MRN" required id="form-postgreSQL-test-MRNInput" required name="TestMRN">
                                    <span class="Form ErrorMessage" id="form-postgreSQL-test-MRNError"></span><br>
                                </div>

                                <!---Date of Birth:-->
                                <div class="FormItem InputBox">
                                    <input type="text" placeholder="Date of Birth (YYYY-MM-DD)" class="Datepicker" required id="form-postgreSQL-test-DOBDatepicker" required name="TestDateOfBirth">
                                    <span class="Form ErrorMessage" id="form-postgreSQL-test-DOEBError"></span><br>
                                </div>
                    
                                <!---Submit button:-->
                                <button type="submit" class="FormItem BtnRegWhiteBackground" id="btn-form-postgreSQL-test-addClients-submit">Submit</button>
                            </form>
                        </div>
                    </div>
                    

I also have <script src="wf_PostgreSQL.js"></script> at the bottom on my “wf_App.html”

This is my “wf_PostgreSQL.js”


/* --------------- STEP 1: RENDERING THE FORM --------------- */ 
const express = require('express');
const app = express();
const port = 9000;

const bodyParser = require('body-parser'); 

app.use(express.static(__dirname));

app.get("/", (req, res) => {
  res.sendFile("file://" + __dirname + "/wf_App.html");
});

app.use(bodyParser.urlencoded({extended: false}))
app.get('/submit',function(req,res){
  console.log("Data Saved");
})



/* --------------- STEP 2: SETUP DATABASE FOR CONNECTION --------------- */ 
/* --------------- Step 2a: Import "Pool" class from the 'pg' (PostgreSQL) Library --------------- */ 
const { Pool, Client } = require('pg');
    // Explanation:  This class is used to manage connections to the PostgreSQL database.

/* --------------- Step 2b: Method 2 - PostgreSQL Connection Set up --------------- */ 
const myPostgresqlConnectionVar = 'postgresql://postgres:mypassword@localhost:5432/My database name'
const client = new Client({
    connectionString:myPostgresqlConnectionVar
})




/* --------------- STEP 3: "POST" FUNCTION LEADING TO INSERTING DATA --------------- */ 
app.post("/",(req,res)=>{
  const { 
      TestLastName,
      TestFirstName,
      TestMRN,
      TestDateOfBirth
  }=req.body
      // Note: Make sure to use the form's names.
  
  client.connect()
    
  client.query(
    'INSERT INTO public.test VALUES ($1, $2, $3, $4)', 
    [TestLastName, TestFirstName, TestMRN, TestDateOfBirth], 
    (err,res)=> {
      console.log(err,res);
      client.end() 
      //alert("Data Saved");        
  })
 
  //res.sendFile(__dirname + "/wf_App.html");
  res.sendFile("file://" + __dirname + "/wf_App.html");
})

app.listen(port, () => {
  console.log(`Console Message: App listening on port ${port}!`)
});

I am expecting that by pressing the submit button that I will see what I wrote in the Form Fields to be added to the corresponding columns in my “test” table in my pgadmin4 (a postgreSQL table) but I get this error in my terminal: 2024-03-09 15:53:26.458 Electron[78711:10876475] WARNING: Secure coding is not enabled for restorable state! Enable secure coding by implementing NSApplicationDelegate.applicationSupportsSecureRestorableState: and returning YES.
(node:78711) electron: Failed to load URL: file:/// with error: ERR_FILE_NOT_FOUND
(Use Electron --trace-warnings ... to show where the warning was created)

Ultimately, I don’t see my data getting added to my pgadmin4 table.

setTimeout function does not affect anything

So I am trying to use setTimeout on one of the functions triggered by a button, but no matter how I format it or where I put it, it just doesn’t work.

On the website, there is a magic 8 ball a user would click, the animation would play, and then 3 seconds later (that’s how long the animation is) a popup with an answer would appear. Everything works except the delay for a popup to appear. No matter if I use the setTimeout function or not, the popup appears right away after clicking the button. Is there something I am missing or doing wrong?

Any help would be appreciated!

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Magic 8 Ball</title>
    <link rel="stylesheet" href="./style.css">
  </head>
    <body>  
        <h1>Magic 8 Ball</h1>
        <p>Ask a question and click on the Magic 8 Ball to reveal the answer</p>
        
        <div class = "8ball">
            <button id = "8bbtn" onclick="spin(); show()"> 
                <video id="video1" width="800">
                <source src="./media/8ball.mp4" type="video/mp4">
            </video> 
            </button>
        </div>
        
        <div id = 'splashscrn'>
            <h1>THE ANSWER</h1>
        </div>
        
        <script> 
            var myVideo = document.getElementById("video1");
            var popup = document.getElementById("splashscrn");
            
            function spin() {  
                myVideo.play(); 
            }
            
            function show() {
                popup.style.display = 'block';
                setTimeout(show, 3000);
            }
        </script>
        
    </body> 
</html>

Firebase Mobile number Authentication issue

Error : testing.html:20 Uncaught ReferenceError: sendOTP is not defined at HTMLButtonElement.onclick (testing.html:20:51) onclick @ testing.html:20

I am trying to build a test Mobile number and OTP ver. website using firebase. I am getting this error in console when i am inserting the mobile number and clicking Send OTP button.

My HTML code:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Firebase OTP Verification</title>
    <!-- Add Firebase SDK -->
    <script src="https://www.gstatic.com/firebasejs/9.6.10/firebase-app-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.6.10/firebase-auth-compat.js"></script>
    <script src="https://www.gstatic.com/firebasejs/9.6.10/firebase-auth-recaptcha-compat.js"></script>

    <!-- Include your separate script -->
    <script src="firebase-script.js" type="module"></script>
</head>
<body>
    <h1>OTP Verification</h1>
    <form id="otpForm">
        <label for="phoneNumber">Phone Number:</label>
        <input type="tel" id="phoneNumber" required>
        <button type="button" onclick="sendOTP()">Send OTP</button>

        <label for="otp">Enter OTP:</label>
        <input type="text" id="otp" required>
        <button type="button" onclick="verifyOTP()">Verify OTP</button>
    </form>
</body>
</html>

My JavaScript code:-

// firebase-script.js
import { initializeApp } from 'https://www.gstatic.com/firebasejs/9.6.10/firebase-app.js';
import { getAuth, signInWithPhoneNumber, RecaptchaVerifier } from 'https://www.gstatic.com/firebasejs/9.6.10/firebase-auth.js';

const firebaseConfig = {
    apiKey: "AIzaSyC01PgXhZ9-9BP01GTWJSs473fmGz5n7Kk",
    authDomain: "otp-verification-27a65.firebaseapp.com",
    projectId: "otp-verification-27a65",
    storageBucket: "otp-verification-27a65.appspot.com",
    messagingSenderId: "25699686034",
    appId: "1:25699686034:web:b56ff82c6a8685d57cf84b",
    measurementId: "G-P0YV1RSGXT"
};

// Initialize Firebase
const firebaseApp = initializeApp(firebaseConfig);
const auth = getAuth(firebaseApp);

function sendOTP() {
    const phoneNumber = document.getElementById('phoneNumber').value;
    const appVerifier = new RecaptchaVerifier('otpForm');

    signInWithPhoneNumber(auth, `+${phoneNumber}`, appVerifier)
        .then((confirmationResult) => {
            window.confirmationResult = confirmationResult;
            console.log("OTP Sent!");
        })
        .catch((error) => {
            console.error("Error sending OTP: ", error.message);
        });
}


function verifyOTP() {
    const otp = document.getElementById('otp').value;
    window.confirmationResult.confirm(otp)
        .then((result) => {
            console.log("OTP Verified!");
        })
        .catch((error) => {
            console.error("Error verifying OTP: ", error.message);
        });
}

I want that the OTP gets verified and the page is redirected to another webpage.

SSR in nextjs witn TS not happening properly

I am using TypeScript to handle SSR for my site. I have written this code for handling api requests for urls of type /Reveal/[slug]. But it gives error while building.
Tell me a way to build my code without this error reappearing again and again. I am not also understanding the exact usecase of GETSTATICPATHS & GETSTATICPROPS here.

generated error

import { useRouter } from "next/router";
import { FC } from "react";
import { medias, label_names, label_descriptions, bg_colors, text_colors } from "..";
import Image from "next/image";
import { GetStaticPaths, GetStaticProps } from "next";

type Props = {

}

const Reveal: FC<Props> = () => {
    const router = useRouter();
    const { slug } = router.query;

    if (router.isFallback) {
        return (<div>isLoading!!!</div>)
    }

    return (<>
        <div className={bg_colors[Number(slug)] + " h-screen w-screen flex"}>
            <div className="w-1/2 p-10 h-screen flex items-center justify-center">
                <Image src={medias[Number(slug)]} alt={label_names[Number(slug)]} height={medias[Number(slug)].height * 2} width={medias[Number(slug)].width * 2} />
            </div>
            <div className="w-1/2 p-10 h-screen flex flex-col items-center justify-center">
                <div className={"font-hipnouma text-[40em] mix-blend-exclusion title " + text_colors[Number(slug)]}>
                    {Number(slug) + 1 + ".) " + label_names[Number(slug)].toUpperCase()}
                </div>
                <div className={"font-lostar text-[7em] mix-blend-color-dodge " + text_colors[Number(slug)]}>
                    {label_descriptions[Number(slug)]}
                </div>
            </div>
        </div>
    </>)
}

type ParamsPaths = {
    id : string
}

export const getStaticPaths: GetStaticPaths<ParamsPaths> = async () => {
    const paths = label_names.map((el, index) => ({ params: { id : index.toString() } }))

    return {
        paths,
        fallback: false
    }
}

export const getStaticProps: GetStaticProps<Props, ParamsPaths> = async ({ params }) => {
    try {
        if (!params)
            throw new Error("params not provided!!!")

        const res = await fetch(`/Reveal/${params.id}`)

        if (!(res.ok))
            throw new Error(`failed to fetch data from API. Status : ${res.status}`)

        const post = await res.json()

        return {
            props: { post }
        }
    }
    catch (error) {
        throw new Error(`Error in GetStaticProps. ${error}`)
    }
}

export default Reveal