The last overload gave the following error. (Overload Error) all the functions I have used are all async

This typescript error occurred in my code:

No overload matches this call. The last overload gave the following error.

 Argument of type '(req: Request, res: Response) => Promise<Response<any, Record<string, any>>>' is not assignable to parameter of type 'Application<Record<string, any>>'.
      Type '(req: Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>) => Promise<...>' is missing the following properties from type 'Application<Record<string, any>>': init, defaultConfiguration, engine, set, and 63 more.ts(2769)
import { Router } from "express";
import * as urlController from "../controllers/urlController";

const router = Router();
 
router.post("/", urlController.createShortUrl);
router.post("/:shortUId", urlController.deleteShortUrl);
export default router;

How to specify a parameter as a function from a specific class in JSDoc?

I’m working on a JavaScript class and using JSDoc for documentation. In the constructor, I have a parameter mutationAlgorithm that should accept a function from the Mutation class (e.g., Mutation.insert()). Here’s my current constructor:

/**
 * @param {???} mutationAlgorithm - A function from the Mutation class.
 */
constructor(mutationAlgorithm = Mutation.insert) {
    this.mutationAlgorithm = mutationAlgorithm;
}

// Usage:
const obj = new Class(Mutation.insert);

I want to specify in the JSDoc that:

  1. This parameter is a function
  2. This function must be from Mutation class

What is the correct JSDoc syntax for this?

Select2: “Cannot read properties of undefined” when prepending/unshifting data on scroll up

I’m using Select2 and trying to implement a feature where new data is prepended or unshifted to the dropdown options when the user scrolls up. However, I’m encountering the errors “Cannot read properties of undefined (reading ‘_resultId’)” and when I select that prepended option shows error “Cannot read properties of undefined (reading ‘id’)”.

    let isLoading = false;
    function loadMoreData(params) {
      if (isLoading || !isAjaxEnabled || page <= 1) {
        return; 
      }
    
      isLoading = true;
    
      $.ajax({
        url: `${apiHost}example`,
        method: 'GET',
        data: {
          text: params.term,
          page: params.page
        },
        success: function(data) {
          console.log('Received new data:', data);
    
          const $resultsList = $('#select2-multi-select-results');
          const newOptions = data.results.map(item => {
            console.log('Creating new option:', item);
            return $('<li class="select2-results__option" role="option" aria-selected="false" data-select2-id="' + item.id + '">' + item.text + '</li>');
          });
          $resultsList.prepend(newOptions);
          console.log('Prepended new options:', newOptions);

          $('.multi-select2').select2('data', data);
          console.log('Updated Select2 data');
    
          isLoading = false;
        },
        error: function() {
          console.error('Error loading more data');
          isLoading = false; 
        }
      });
    }

    $('.multi-select2').on('select2:open', function() {
        const $dropdown = $('#select2-multi-select-results');
        $dropdown.on('scroll', function() {
          if ($dropdown.scrollTop() < 50 && isAjaxEnabled) {
            loadMoreData();
          }
        });

Error cannot read properties of undefined (reading ‘_resultId’)
select2.js
enter image description here

Error cannot read properties of undefined (reading ‘id’)
select2.js
enter image description here

I’ve tried various approaches, but I’m still getting the errors. I suspect it might be related to the data structure or how I’m handling the Select2 results.

How can I ensure that the _resultId and id properties are defined in the data I’m receiving?
What’s the correct way to prepend or unshift new data to the Select2 options?
Are there any specific configuration settings or event handlers I need to consider for this functionality?

How do i bundle my React app as full files with electron-builder

I have a React Electron application that currently builds and runs off the built html file of my react app. For ease of hot fixes/updates (this is an internal tool), id like to have the build of the electron app use the entire react app and bundle in those files and run the react server. Is there an easy way to do that?

Here is Package.Json

  "name": "testapp",
  "version": "1.0.1",
  "author": "author",
  "description": "testapp client application.",
  "homepage": ".",
  "private": true,
  "dependencies": {
    "@testing-library/jest-dom": "^5.17.0",
    "@testing-library/react": "^13.4.0",
    "@testing-library/user-event": "^13.5.0",
    "bootstrap": "^5.3.3",
    "concurrently": "^8.2.2",
    "cross-env": "^7.0.3",
    "react": "^18.2.0",
    "react-bootstrap": "^2.10.2",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.22.3",
    "react-scripts": "5.0.1",
    "wait-on": "^7.2.0",
    "web-vitals": "^2.1.4"
  },
  "devDependencies": {
    "electron": "^30.0.9"
  },
  "scripts": {
    "start-react": "react-scripts start",
    "build-react": "react-scripts build",
    "test": "react-scripts test",
    "eject": "react-scripts eject",
    "start-electron": "electron .",
    "start": "concurrently "cross-env BROWSER=none npm run start-react" "wait-on http://127.0.0.1:3000 && npm run start-electron"",
    "build": "npm run build-react && electron-builder -w -c.extraMetadata.main=build/electron.js"
  },
  "eslintConfig": {
    "extends": [
      "react-app"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "electron": "electron .",
  "main": "public/electron.js",
  "build": {
    "extends": null,
    "appId": "com.testapp.app",
    "productName": "testapp",
    "files": [
      "public/**/*",
      "dist/**/*",
      "build/**/*",
      "node_modules/**/*",
      "package.json"
    ],
    "directories": {
      "buildResources": "public",
      "output": "build"
    },
    "win": {
      "target": "nsis",
      "icon": "testappLogo.png"
    },
    "extraResources": {
            "filter": ["./config.json"]
        }
  }
}

Electron.js:

const path = require('path');
const fs = require('fs');

const isPackaged = app.isPackaged;

//force dark mode electron ui
nativeTheme.themeSource = "dark"

function createWindow () {
  const win = new BrowserWindow({
    width: 1500,
    height: 600,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule:true,
      preload: path.join(__dirname, 'preload.js'),
    },
    title:"TestApp"
  })

  //Open devTools in dev 
  if(!isPackaged){
    win.webContents.openDevTools("detach", false, "DevTools");
  }

  //load the index.html from a url
  win.loadURL(
  !isPackaged 
    ? 'http://localhost:3000'
   : 
    `file://${path.join(__dirname, '../build/index.html')}`
    );
}

function helpWindow(){
  const helpWin = new BrowserWindow({
    width: 800,
    height: 500,
    webPreferences: {
      nodeIntegration: true,
      enableRemoteModule:true,
    },
    title:"About This Version"
  })

  //load the index.html from a url
  helpWin.loadURL(`file://${path.join(__dirname, '../build/help.html')}`);
}

const menu = [
  {
    label: 'App',
    submenu: [
      { label: 'Quit', role: 'quit'},
    ]
  },
  {
    label: 'WebPage',
    submenu: [
      { label: 'DevTools', role: 'toggleDevTools', accelerator: 'f12'},
      { label: 'Reload', role: 'reload', accelerator: 'f5'},
      { label: 'ForceReload', role: 'forceReload', accelerator: 'ctrl+f5'}
    ]
  },
  {
    label: 'About This Version',
    click: helpWindow,
  }
]

app.whenReady().then(async() => {
  createWindow();
  const electronMenu = Menu.buildFromTemplate(menu);
  Menu.setApplicationMenu(electronMenu);

  app.on('activate',async () => {
    if (BrowserWindow.getAllWindows().length === 0) {
      createWindow()
    }
  })
});

ipcMain.handle('get-config', async (event) => {
    try {
      if(!isPackaged){ 
         return { 'apiUrl' : 'http://localhost:2223'}
      } else {
        const configPath = path.join(process.resourcesPath, 'config.json');
        const data = fs.readFileSync(configPath, 'utf-8');
        return JSON.parse(data);
      }
    } catch (err) {
        console.error("Failed to load config", err);
        return { error: 'Failed to load config file' };
    }
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

Time fluctuating

// Determine next month and year
$nextMonthDate = new DateTime('first day of next month');
$nextMonthName = $nextMonthDate->format('F');
$nextYear = $nextMonthDate->format('Y');

// ...

$currentDate = new Date();
const currentDay = currentDate.getDate();

if (currentDay <= 7) {
    currentTimerText = 'Time Remaining';
    upcomingTimerText = 'Registration Starts';
}else{
    currentTimerText = 'Registration Closed';
    upcomingTimerText = 'Registration Ends';
}

// ...

const currentTimerEnd = new Date(currentYear, currentMonth, Math.min(7, lastDayOfCurrentMonth), 23, 59, 59);
const upcomingTimerEnd = new Date(upcomingMonthYear, upcomingMonth, Math.min(7, lastDayOfUpcomingMonth), 23, 59, 59);

// ...

function calculateTimeRemaining(endDate) {
    const now = new Date();
    const timeRemaining = endDate - now;
    const days = Math.floor(timeRemaining / (1000 * 60 * 60 * 24));
    const hours = Math.floor((timeRemaining % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
    const minutes = Math.floor((timeRemaining % (1000 * 60 * 60)) / (1000 * 60));
    const seconds = Math.floor((timeRemaining % (1000 * 60)) / 1000);
    return {
        days,
        hours,
        minutes,
        seconds
    };
}

// ...

function startCountdown(element, endDate) {
    function updateCountdown() {
        const { days, hours, minutes, seconds } = calculateTimeRemaining(endDate);
        element.innerHTML = `
            <div class="m-table__itm"><span>${days}</span><span>DAYS</span></div>
            <div class="m-table__itm"><span>${hours}</span><span>HRS</span></div>
            <div class="m-table__itm"><span>${minutes}</span><span>MIN</span></div>
            <div class="m-table__itm"><span>${seconds}</span><span>SEC</span></div>
        `;
        if (endDate > new Date()) {
            setTimeout(updateCountdown, 1000);
        } else {
            element.innerHTML = '<div class="m-table__itm"><span>-</span><span>DAYS</span></div><div class="m-table__itm"><span>-</span><span>HRS</span></div><div class="m-table__itm"><span>-</span><span>MIN</span></div><div class="m-table__itm"><span>-</span><span>SEC</span></div>';
        }
    }
    updateCountdown();
}

// ...

const currentEndDate = new Date(currentDate.getFullYear(), currentMonth + 1, 0, 23, 59, 59);
const upcomingEndDate = new Date(currentDate.getFullYear(), currentMonth + 2, 0, 23, 59, 59);

// ...

if (currentDay <= 7) {
    startCountdown(document.getElementById('countdown-0'), currentTimerEnd);
    startCountdown(document.getElementById('countdown-1'), currentTimerEnd);
}else{
    startCountdown(document.getElementById('countdown-0'), currentTimerEnd);
    startCountdown(document.getElementById('countdown-1'), upcomingTimerEnd);
}

I am using this code for a competition, and it includes a countdown timer. The problem I’m facing is that the countdown time is fluctuating. For example, it should show 5 days, 10 hours, 3 minutes, and 45 seconds, but for a second, it shows 59 days, 10 hours, 3 minutes, and 45 seconds. This flicker in the days occurs every time it counts down. I’m not sure why this is happening. Please help me resolve this issue.

How can I ‘translate’ this Python function into JavaScript?

Given a Pandas dataframe df which has the following form:

Year Month Run Hours Site Factor
2021 10 62.2 Site A 1.50451
2024 2 73.6 Site B 2.30281

…etc. (the actual dataframe has about three years of data for five sites with entries for each month of each year)

How can I write in JavaScript some code which is equivalent to this function in Python?

def function(month, site, rhours):
    df1 = df.loc[(df.Month == month) & (df.Site == site) & (df['Run Hours'] <= rhours)]
    factor = df1.loc[df1['Run Hours'] == max(df1['Run Hours']), 'Factor'].item()

The python function takes inputs of a month, site and number of run hours. If then filters df to only the data from those months (across however many years there are) and for that site with run hours <= to the input rhours – this is df1.

From df1, it then finds the row with the largest number of run hours and sets the factor variable to be the Factor entry of that row.

Could somebody please ‘translate’ this into JavaScript? My JS is pretty basic but I’ve tried using this (built up of Frankensteining examples I’ve found elsewhere online) but I don’t think it really works

const dataframe = df

function getFactorForMaxRunHours(df, month, site, rhours) {
    // Step 1: Filter dataframe by the provided month and site
    const df1 = df.filter(row => row.Month === month);

    // Step 2: Sort filtered data by 'Run Hours' in ascending order
    const sortedData = df1.sort((a, b) => a.RunHours - b.RunHours);

    // Step 3: Find the maximum 'Run Hours' that is still less than 'runHoursInput'
    let maxRunHoursEntry = null;
    for (let entry of sortedData) {
        if (entry.RunHours < Rhours) {
            maxRunHoursEntry = entry;
        } else {
            break; // Since it's sorted in ascending order, we can break early
        }
    }

    // Step 4: Return the 'Factor' if an entry was found, else return null
    return maxRunHoursEntry ? maxRunHoursEntry.Factor : null;
}

How can I call a custom JavaScript function, to manipulate the HTML5 canvas element, from within the “HTML” section of my Blazor server project?

I have a Blazor server application. On one of my pages I have the standard setup:

MyPage.razor:

@page "/mypage"
<div>
    <!-- stuff here ... -->
</div>

@code {
    // stuff here ...
}

On this page, I am looping through a List like so:

<div>
    @foreach(MyData anData in ListOfMyData){
        // stuff here ...
    }
</div>

Within this loop, I want to create an image with the HTML canvas element based off the data within MyData.

<div>
    @foreach(MyData anData in ListOfMyData){
        <div>
            <canvas id="@anData.id" class="myDataImage"></canvas>
        </div>
    }
</div>

Within the @code section, I am injecting IJSRuntime:

@code {
    [Inject]
    IJSRuntime JSRuntime { get; set; }
}

And I have my JavaScript code in: MyApp/wwwroot/js/MyJavaScript.js

function drawImage(canvasID, data){
    let thisCanvas = document.getElementById(canvasID);
    thisCanvas.width = xxx;
    thisCanvas.height = xxx;
    let ctx = thisCanvas.getContext('2d');
    ctx.beginPath();
    // ... more here
}

“Individually”, this all works, meaning:

  1. I have successfullly used IJSRuntime before with other custom JavaScript fuctions.
  2. The JavaScript I have works, as I have tested it in a “vanilla” HTML project.

What I am having trouble figuring out is how to call the JavaScript function from within the “HTML” section of my Blazor (.razor) page.

javascript check if php page in iframe reloads [closed]

I have an Angular project, where I have an iframe that contains a PHP project.
I want to show a loading spinner when something in the iframe is changing. That means I want a notification in my Angular Javascript if the PHP code reloads the page.
I have no access to the PHP code.
Is there a way to do this?

Issue when validating checkbox in Javascript

I’ve created a custom contact form for a website using WordPress.

All the fields are required to send the form. In case of an error, the validation is done in Javascript to avoid reloading the page. All the validation fields work fine less one, the checkbox.

The issue I guess is in the javascript where I tried to check if the checkbox has been checked or not.

The PHP function to create the form:

<?php
add_shortcode( 'contact-form', 'site_contact_form' );
function site_contact_form() {

    $validation_messages = [];
    $success_message = '';

    if ( isset( $_POST['contact_form'] ) ) {

        //Sanitize the data
        $firstname = isset( $_POST['firstname'] ) ? sanitize_text_field( $_POST['firstname'] ) : '';
        $surname = isset( $_POST['surname'] ) ? sanitize_text_field( $_POST['surname'] ) : '';
        $email = isset( $_POST['email'] ) ? sanitize_text_field( $_POST['email'] ) : '';
        $phone = isset( $_POST['phone'] ) ? sanitize_text_field( $_POST['phone'] ) : '';
        $acceptance = isset( $_POST['acceptance'] ) ? sanitize_text_field( $_POST['acceptance'] ) : '';

        //Validate the data
        if ( strlen( $firstname ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un nombre.', 'sobrado' );
        }

        if ( strlen( $surname ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un apellido.', 'sobrado' );
        }

        if ( strlen( $email ) === 0 or
             ! is_email( $email ) ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un email válido.', 'sobrado' );
        }

        if ( strlen( $phone ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor introduzca un teléfono.', 'sobrado' );
        }

        if ( strlen( $acceptance ) === 0 ) {
            $validation_messages[] = esc_html__( 'Por favor marca la casilla.', 'sobrado' );
        }

        //Send an email to the WordPress administrator if there are no validation errors
        if ( empty( $validation_messages ) ) {

            //$mail    = get_option( 'admin_email' );
            $to    = '[email protected]';
            $subject = 'Nuevo mensaje de ' . $firstname .' '. $surname;
            $message = 'El email del cliente es: ' . $email;

            wp_mail( $to, $subject, $message );

            $success_message = esc_html__( 'Su mensaje ha sido enviado con éxito.', 'sobrado' );

        }

    }

    //Display the validation errors
    if ( ! empty( $validation_messages ) ) {
        foreach ( $validation_messages as $validation_message ) {
            echo '<div class="c-form__validation-message">' . esc_html( $validation_message ) . '</div>';
        }
    }

    //Display the success message
    if ( strlen( $success_message ) > 0 ) {
        echo '<div class="c-form__success-message">' . esc_html( $success_message ) . '</div>';
    }

    ?>

    <div id="validation-messages-container" class="c-form__validation"></div>

    <form id="contact-form" class="c-form__form" action="<?php echo esc_url( get_permalink() ); ?>" method="post">

        <input type="hidden" name="contact_form">

        <div class="c-form__section c-form__section--firstname">
            <label for="firstname" class="c-form__label"><?php echo esc_html( 'Nombre', 'sobrado' ); ?></label>
            <input type="text" id="firstname" class="c-form__input" name="firstname" placeholder="<?php echo esc_html( 'Nombre', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--surname">
            <label for="surname" class="c-form__label"><?php echo esc_html( 'Apellidos', 'sobrado' ); ?></label>
            <input type="text" id="surname" class="c-form__input" name="surname" placeholder="<?php echo esc_html( 'Apellidos', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--phone">
            <label for="phone" class="c-form__label"><?php echo esc_html( 'Telefóno', 'sobrado' ); ?></label>
            <input type="text" id="phone" class="c-form__input" name="phone" placeholder="<?php echo esc_html( 'Telefóno', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--email">
            <label for="email" class="c-form__label"><?php echo esc_html( 'Email', 'sobrado' ); ?></label>
            <input type="email" id="email" class="c-form__input" name="email" placeholder="<?php echo esc_html( 'Email', 'site' ); ?>">
        </div>

        <div class="c-form__section c-form__section--footer">
            <div class="c-form__section c-form__section--acceptance">
                <input type="checkbox" id="acceptance" class="c-form__checkbox" name="acceptance" value="Yes">
                <label for="acceptance" class="c-form__label c-form__label--acceptance"><?php echo esc_html( 'Al confirmar mis datos acepto la política de privacidad y términos y condiciones.', 'site' ); ?></label>
            </div>
            <input type="submit" id="contact-form-submit" class="c-form__submit" value="<?php echo esc_attr( 'Enviar', 'site' ); ?>">
        </div>

    </form>

    <?php
}
?>

The JS:

const contactFormSubmit = document.getElementById('contact-form-submit');

if(contactFormSubmit){

    contactFormSubmit.addEventListener('click', validateForm);

    function validateForm(event) {

        event.preventDefault();
        event.stopPropagation();

        // Name
        const firstname = document.getElementById('firstname') !== null ?
        document.getElementById('firstname').value :
        '';

        // Surname
        const surname = document.getElementById('surname') !== null ?
        document.getElementById('surname').value :
        '';

        // Phone
        const phone = document.getElementById('phone') !== null ?
        document.getElementById('phone').value :
        '';

        // Email
        const email = document.getElementById('email') !== null ?
        document.getElementById('email').value :
        '';      '';

        // Checkbox
        const acceptance = document.getElementById('acceptance') !== false ?
        document.getElementById('acceptance').value : 
        '';

        const validationMessages = [];
        if (firstname.length === 0) {
            validationMessages.push('Por favor introduzca un nombre.');
        }

        if (surname.length === 0) {
            validationMessages.push('Por favor introduzca un apellido.');
        }

        if (phone.length === 0) {
            validationMessages.push('Por favor introduzca un teléfono.');
        }

        if (email.length === 0 || !emailIsValid(email)) {
            validationMessages.push('Por favor introduzca un email válido.');
        }

        if (acceptance.checked == false) {
            validationMessages.push('Por favor marca la casilla.');
        }

        if (validationMessages.length === 0) {

            //Submit the form
            document.getElementById('contact-form').submit();

        } else {

            //Delete all the existing validation messages from the DOM
            const parent = document.getElementById('validation-messages-container');
            while (parent.firstChild) {
                parent.removeChild(parent.firstChild);
            }

            //Add the new validation messages to the DOM
            validationMessages.forEach(function(validationMessage, index) {

                //add message to the DOM
                const divElement = document.createElement('div');
                divElement.classList.add('validation-message');
                const node = document.createTextNode(validationMessage);
                divElement.appendChild(node);

                const element = document.getElementById('validation-messages-container');
                element.appendChild(divElement);

            });

        }

    }

    /**
    * A simple function that verify the email with a regular expression.
    *
    * @param email
    * @returns {boolean}
    */
    function emailIsValid(email) {

        const regex = /S+@S+.S+/;
        return regex.test(email);

    }
}

Thank you.

Trigger a rerender when window.location.search changes

I created a button that changes my route and adds a search param to the URL.

The functionality of the button is as so:

import { Link } from "react-router-dom";

<Link to={`/route/locations?openCertainModal=true`}>
  {placeholder}
</Link>

My problem occurs when I am already in the located in /route/locations. When I click the button and I’m there, the route will change from /route/locations to /route/locations?openCertainModal=true, but since the component is already mounted, no rerender is triggered. How can I trigger a rerender of the component when ?openCertainModal=true is added to the route and window.location.search changes?

Get LinkedIn Education and Employment histories

I’m building an app that gets LinkedIn profile, education and employment data.

First, I request LinkedIn profile access from:
https://www.linkedin.com/oauth/v2/authorization?response_type=code&client_id=id&redirect_uri=uri&state=state&scope=profile%20email%20openid

Then I get the access token from https://www.linkedin.com/oauth/v2/accessToken

And I use returned access token to call this API but failed: https://www.linkedin.com/oauth/v2/me

  • status: 403
  • serviceErrorCode: 100
  • code: ‘ACCESS_DENIED’
  • message: ‘Not enough permissions to access: me.GET.NO_VERSION’

Besides, is it possible to get education and employment from a linkedin profile?

I have checked the docs but did not see anything related to the issue.

Unable to Access req.user in Backend and Frontend After Successful Login

I’m working on a project where users can log in and view/edit data based on their role (Admin or regular user). After successful login, a JWT is generated and sent to the frontend, but I can’t seem to access the req.user in either the backend or frontend properly.

Backend Setup
In my backend, I use JWT for authentication. When a user logs in, a token is generated, and I attach it to the cookies.

Here’s my backend login route:

    const { usernameOrEmail, password } = req.body;

    try {
        const user = await User.findOne({
            where: {
                [Op.or]: [{ email: usernameOrEmail }, { username: usernameOrEmail }]
            }
        });

        if (!user) {
            return res.status(400).json({ message: 'Invalid username or email' });
        }

        const isMatch = await bcrypt.compare(password, user.password);
        if (!isMatch) {
            return res.status(400).json({ message: 'Invalid password' });
        }

        const token = jwt.sign({
            id: user.id,
            username: user.username,
            email: user.email,
            role: user.role,
        }, process.env.JWT_SECRET, { expiresIn: '2h' });

        res.cookie('token', token, { httpOnly: true });
        res.status(200).json({
            message: 'Login successful',
            token,
            user: {
                id: user.id,
                username: user.username,
                email: user.email,
                role: user.role,
            }
        });
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

Here’s my middleware for verifying the token:

    const token = req.cookies.token; // Extract JWT token from cookies

    if (!token) {
        return res.status(401).json({ message: 'Access denied. No token provided.' });
    }

    try {
        const decoded = jwt.verify(token, process.env.JWT_SECRET);
        req.user = decoded;  // Attach user data to req.user
        next();
    } catch (error) {
        return res.status(403).json({ message: 'Invalid token.' });
    }
};

Frontend Setup (on a different port)
After login, I’m trying to fetch the user data in the frontend and display admin-specific links (e.g., edit brands).

Here’s the frontend login logic:

    try {
        const response = await fetch('http://localhost:3000/api/auth/login', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ usernameOrEmail, password }),
            credentials: 'include'
        });

        if (response.ok) {
            const data = await response.json();
            const decodedToken = jwt_decode(data.token);
            const role = decodedToken.role;

            if (role === 'Admin') {
                window.location.href = '/brands/edit';
            } else {
                window.location.href = '/profile';
            }
        } else {
            alert('Login failed');
        }
    } catch (error) {
        console.error('Error during login:', error);
        alert('Login failed: ' + error.message);
    }
}

And I’m trying to fetch the user data like this:

    try {
        const response = await fetch('http://localhost:3000/api/auth/user', {
            method: 'GET',
            credentials: 'include',  // Include the cookie with the token
            headers: {
                'Content-Type': 'application/json'
            }
        });

        if (response.ok) {
            const data = await response.json();
            return data.user;
        } else {
            console.log('Failed to fetch user data');
            return null;
        }
    } catch (error) {
        console.error('Error fetching user data:', error);
        return null;
    }
}

document.addEventListener('DOMContentLoaded', async function() {
    const user = await fetchUser();
    if (user && user.role === 'Admin') {
        console.log('Admin user:', user);
        document.getElementById('admin-links').style.display = 'block';
    } else {
        console.log('Non-admin or guest user:', user);
    }
}); 

Problem
Even after the login is successful (verified by inspecting the token in the browser’s Application tab), the req.user remains undefined in both the frontend and backend. I can see the token and its payload in the browser, but when I try to access protected routes or display admin-specific content, it doesn’t recognize the user.

In the backend, req.user is undefined in the route that requires user authentication, and in the frontend, fetchUser() always returns null.

I’ve confirmed that the token is being set in the cookies, and it contains the correct user data.

Questions:
Why is req.user undefined in the backend even though the token is being set and sent in the cookies?
Why is fetchUser() returning null or failing to fetch the logged-in user on the frontend?
Any help or guidance would be greatly appreciated!

select elements memorized by the browser [duplicate]

I have a simple form with two input fields (first for location and second for password), a validation button and a function letsGo called at the time of submission :

<form id="form">
    <input id="rememberMe" required type="text" autocomplete="on" autofocus />
    <input id="forgetMe" required type="password" autocomplete="off" />
    <input id="button" type="submit" value="go" />
</form>
<script>
form.addEventListener("submit", letsGo);
function letsGo(event) {
    event.preventDefault();
    // processing...
}
</script>

I’d like the browser to memorize only the first field rememberMe.

when I open, fill in and validate the form below from the browser (FireFox), it asks me if I want to save the location/password pair, which I don’t want to do.

if I change the second input field to text type, my wish is granted, but the password is no longer masked, which I don’t want.

if, after this change, I add at the forgetMe.type = "password"; line at the beginning of the code block to dynamically modify the type of the second field after the form has been “defined”, the browser asks me again if I want to save the location/password pair, which I don’t want.

going back to the original code, if I try to dynamically modify the type of the second field to text just before submission by adding the following code forgetMe.value = ""; forgetMe.type = "text"; at the beginning of the letsGo function, the browser continues to ask me if I want to save the login/password pair (and password is not empty as expected), which I don’t want.

similarly, if I try to operate in the button’s click event which precedes the form’s submit event, it doesn’t work either.

so how can I get the browser to memorize only the first field ?

Add Ability for a Gradient Background in Vanta JS

Good Day!

I need to replace the solid background color in the VANTA JS (HALO Animation) with a gradient background instead.

This is my workaround with the help of ChatGPT (I’m not sure how it’ll replace developers, haha!).

This is just a test using non-customizable code, but once it works, I’ll add new options for colors.

— FILE: vanta.halo.js

New functions: addGradientBackground and updateGradientResolution

addGradientBackground() {
    // Create custom gradient shader material
    const gradientShaderMaterial = new THREE.ShaderMaterial({
      uniforms: {
        resolution: { type: 'v2', value: new THREE.Vector2() }  // Placeholder for the resolution
      },
      vertexShader: `
        void main() {
          gl_Position = vec4(position, 1.0);
        }
      `,
      fragmentShader: `
        uniform vec2 resolution;
  
        void main() {
          // Calculate the normalized coordinate (0.0 to 1.0)
          vec2 uv = gl_FragCoord.xy / resolution.xy;
  
          // Gradient colors (rgb(249, 38, 225) and rgb(42, 181, 251))
          vec3 color1 = vec3(249.0 / 255.0, 38.0 / 255.0, 225.0 / 255.0);
          vec3 color2 = vec3(42.0 / 255.0, 181.0 / 255.0, 251.0 / 255.0);
  
          // Smooth interpolation between colors based on the x-axis (uv.x)
          vec3 color = mix(color1, color2, smoothstep(0.22, 0.9976, uv.x));
          
          gl_FragColor = vec4(color, 1.0);
        }
      `
    });  
  
    // Create a plane geometry for the full screen
    const planeGeometry = new THREE.PlaneGeometry(2, 2);
    const backgroundPlane = new THREE.Mesh(planeGeometry, gradientShaderMaterial);
  
    // Push the plane behind the HALO effect
    backgroundPlane.position.z = -1;
    
    // Add the plane to the HALO scene
    this.scene.add(backgroundPlane);
  }

  updateGradientResolution() {
    // Get the current width and height from the renderer or camera
    const width = this.renderer.domElement.width;
    const height = this.renderer.domElement.height;
  
    // Update the uniform for the shader material
    const gradientShaderMaterial = this.scene.children.find(child => child.material && child.material.uniforms && child.material.uniforms.resolution);
    if (gradientShaderMaterial) {
      gradientShaderMaterial.material.uniforms.resolution.value.set(width, height);
    }
  }


onInit() {
    const pars = { minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter, format: THREE.RGBFormat }
    const ww = this.width * window.devicePixelRatio / this.scale
    const hh = this.height * window.devicePixelRatio / this.scale

    // Now, insert custom gradient shader logic here for HALO only
    this.addGradientBackground();
    
    this.bufferTarget = new THREE.WebGLRenderTarget( ww, hh, pars )
    this.bufferFeedback = new THREE.WebGLRenderTarget( ww, hh, pars )

  }

onResize() {
    if (this.bufferTarget) {
      const ww = this.width * window.devicePixelRatio / this.scale
      const hh = this.height * window.devicePixelRatio / this.scale
      
      // Update the resolution of the gradient when the window is resized
      this.updateGradientResolution();

      this.bufferTarget.setSize( ww, hh )
      this.bufferFeedback.setSize( ww, hh )
    }
  }

— Re-produce vanta.halo.min.js

npx webpack --config webpack.config.js