Express route returning no value as function is not executed

I am struggling with some Express routs that behave differently even though the code to execute is the same.

I want a client application to call the API as follows:

async search(){

      const query = this.$refs.searchInput.value;
      console.log(query);

      const addressToFetch = "/api/budget/search?q=" + query;
      await fetch(addressToFetch)
        .then((response) => response.json())
        .then((response) => {
          console.log(response);
        });
    }

Where the value of query is taken from the following input HTML tag:

              <div class="input-group row text-right">
                <!--flex-nowrap-->
                <div class="col">
                  <input
                    type="text"
                    id="searchInput"
                    name="search"
                    placeholder="Search"
                    ref="searchInput"
                  />
                  <button
                    type="button"
                    class="btn btn-primary btn-search btn-filter"
                    @click="search"
                  >
                    <i class="fa fa-search" aria-hidden="true"></i>
                  </button>

                  <button
                    type="button"
                    class="btn btn-danger"
                    v-if="filteredResults"
                    @click="getExpenses"
                  >
                    Undo
                  </button>
                </div>
              </div>

The server-side application handles the request as follows:

app.get("/api/budget/search", verify, async (req, res) => {
  console.log(req.query.q);
  const users = await db
    .collection("users")
    .find({ username: { $regex: req.query.q } })
    .toArray();
  users.forEach((user) => {
    delete user.password;
  });

  res.json(users);
});

After authentication, this function returns [] and not even server-side logs are printed. Checking with Postman, I can see that the response is 200 OK anyway. I created a different route for testing purposes with the same code inside. It turns out that the new route gives different (good) results:

app.get("/api/users/search", verify, async (req, res) => {
  console.log(req.query.q);
  const users = await db
    .collection("users")
    .find({ username: { $regex: req.query.q } })
    .toArray();
  users.forEach((user) => {
    delete user.password;
  });

  res.json(users);
});

I leave you all the routes to see if there are any problems with it:

const express = require("express");
const fs = require("fs/promises");
const session = require("express-session");
const { MongoClient } = require("mongodb");
const exp = require("constants");
const uri = "mongodb://mongohost";
const app = express();

const client = new MongoClient(uri);
let db = null;

app.use(express.static(`${__dirname}/public`));
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(
  session({
    secret: "segreto",
    resave: false,
  })
);

function verify(req, res, next) {
  if (req.session.user) {
    next();
  } else {
    res.status(403);
  }
}

app.post("/api/auth/signup", async (req, res) => {});

app.post("/api/auth/signin", async (req, res) => {...});

app.get("/api/budget/whoami", verify, (req, res) => {...});

app.get("/api/budget", verify, async (req, res) => {...});

app.get("/api/budget/:year", verify, async (req, res) => {...});

app.get("/api/budget/:year/:month", verify, async (req, res) => {...});

app.get("/api/budget/:year/:month/:id", verify, async (req, res) => {...});

app.post("/api/budget/:year/:month", verify, async (req, res) => {...});

app.put("/api/budget/:year/:month/:id", verify, async (req, res) => {...});

app.delete("/api/budget/:year/:month/:id", verify, async (req, res) => {...});

app.get("/api/balance", verify, async (req, res) => {...});

app.get("/api/balance/:id", verify, async (req, res) => {...});

app.get("/api/budget/search", verify, async (req, res) => {...});


app.get("/api/users/search", verify, async (req, res) => {...});

app.listen(3000, async () => {
  await client.connect();
  db = client.db("balanceApp");
});

I don’t get the problem with the first route, is there anything I can do to fix the problem? Thank you very much for your patience.

Usage of @grpc/proto-loader and proto-loader-gen-types with ES modules

I am are currently trying to migrate my microservices to use ES modules. Everything went great until it was time to migrate those that use the @grpc/proto-loader module as I am unable to generate valid ES module imports.

In the current configuration the proto-loader-gen-types script is use to transform the .proto files to the Typescript types as per documentation and is working fine.

The script used is as follows: proto-loader-gen-types --longs=String --enums=String --defaults --oneofs --grpcLib=@grpc/grpc-js --outDir=./src/protobuild/ ./src/protobuild/*.proto

The main issue is that the generated code looks something similar to this:

import type { ExampleClient as _example_package_ExampleClient, ExampleDefinition as _example_package_ExampleDefinition } from './example_package/Example';

When adding "type": "module" to the package.json and the relevant config to .tsconfig.json file imports similar to the following are expected:

import type { ExampleClient as _example_package_ExampleClient, ExampleDefinition as _example_package_ExampleDefinition } from './example_package/Example.js';

Notice the .js at the end of the import route. In the current state my build step fails with errors like:

Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'. Did you mean './example_package/Example.js'?ts(2835)

Relevant .tsconfig.json settings:

"compilerOptions": {
    "target": "ESNext",
    "module": "NodeNext",
    "declaration": true,
    "sourceMap": true,
    "strict": true,
    "moduleResolution": "NodeNext",
    "esModuleInterop": true,
    "noImplicitAny": true,
    "noImplicitReturns": true,
    "skipLibCheck": true
},

Is there any way to modify the proto-loader-gen-types command to generate valid imports or any other config to be changed?

Note: I do prefer not to include any other tooling/package to the build chain if possible.

uncaught SyntaxError: Unexpected token ‘o’, “[object Obj”… is not valid JSON at JSON.parse

I am making a Budget Tracking App and I have got an error regarding JSON.parse as it is not showing my entered transaction and expenses from localStorage and consoling the error

When refreshing the page, transactions array cannot be found from the localStorage and error occurs

I have tried to make JSON.stringify but it is not working
this is not showing anything in the browser

CODE:
`

 const form=document.querySelector(".add");
    
     let transactions=localStorage.getItem("transactions")!==null? JSON.parse(localStorage.getItem("transactions")):[];
    
    
    
    const incomeList=document.querySelector("ul.income-list");
    const expenseList=document.querySelector("ul.expense-list");
    
    
    const balance=document.getElementById("balance")
    const income=document.getElementById("income");
    const expense=document.getElementById("expense")
    
    function generateTemplate(id,source,amount,time)
    {
        return `<li data-id="${id}">
                                                <p>
                                                    <span>${source}</span>
                                                    <span id="time">${time}</span>
                                                </p>
                                                <span>$ ${Math.abs(amount)}</span>
                                                <i class="bi bi-trash delete">Del</i>
                    </li>`
    }
    function addTransactionDOM(id,source,amount,time)
    {
        if(amount>0){
            incomeList.innerHTML+=generateTemplate(id,source,amount,time)
        }else{
            expenseList.innerHTML+=generateTemplate(id,source,amount,time)
        }
    }
    function addTransaction(source,amount)
    {
        const time=new Date();
        const transaction={
            id:Math.floor(Math.random()*500),
            source:source,
            amount:amount,
            time:`${time.toLocaleTimeString()} ${time.toLocaleDateString()} `
        }
        transactions.push(transaction)
        localStorage.setItem("transactions",JSON.stringify(transactions))
        addTransactionDOM(transaction.id,source,amount,transaction.time)
    }
    
    function getTransaction()
    {
        transactions.forEach((transaction)=>{
            if(transaction.amount>0){
                incomeList.innerHTML+=generateTemplate(transaction.id,transaction.source,transaction.amount,transaction.time)
            }else{
                expenseList.innerHTML+=generateTemplate(transaction.id,transaction.source,transaction.amount,transaction.time)
            }
        })
    }
    
    incomeList.addEventListener("click",e=>{
        if(e.target.classList.contains("delete")){
            //This one is for removing from DOM
            e.target.parentElement.remove();
            //This one is for removing from "transactions" array[]
            deleteTransaction(Number(e.target.parentElement.dataset.id))
        }
    })
    expenseList.addEventListener("click",e=>{
        if(e.target.classList.contains("delete")){
            //This one is for removing from DOM
            e.target.parentElement.remove();
            //This one is for removing from "transactions" array[]
            deleteTransaction(Number(e.target.parentElement.dataset.id))
        }
    })
     function deleteTransaction(id)
     {
         console.log(id);
         transactions=transactions.filter((transaction)=>{
            
             return transaction.id!==id;
        });
         localStorage.setItem("transactions",JSON.stringify(transactions))
     }
    
    
    
    
    function updateStatistics()
    {
        const updatedIncome=transactions.filter((transaction)=>{
            return transaction.amount>0
        }).reduce((total,filteredTransaction)=>{
            return total=total+filteredTransaction.amount
        },0);
    
        const updatedExpense=transactions.filter((transaction)=>{
            return transaction.amount<0;
        }).reduce((total,filteredTransaction)=>{
            return total=total+Math.abs(filteredTransaction.amount)
        },0);
    
        income.textContent=updatedIncome;
        expense.textContent=updatedExpense;
    }
    
    
    
    
    form.addEventListener("submit",(e)=>{
        e.preventDefault();
        addTransaction(form.source.value,Number(form.amount.value))
        form.reset()
        
    });
    
    getTransaction();
    updateStatistics()

`

Carriage return in strings with Node.js

I wrote the following code in Node.js:

sitemap.selection = "n";
for (const deck in series) {
  sitemap.selection += `abcn`
}
console.log (sitemap)

When I run the code, it displays the following in the console:

selection: 'n' +
    'abcn' +
    'abcn' +
    'abcn' +
    'abcn' +
    'abcn' +
    'abcn' +
    'abcn'

Why the string are not concatenated?

createMediaElementSource not playing audio even after connecting source to the destination

As mentioned in the title, after using createMediaElementSource, my audio is not playing even after connecting source to the destination. I was working on a project which uses Meyda’s audio features to help represent these audio visually in an appropriate manner. I am new to Meyda and was trying to replicate their code example to test it out, but it did not work for me.

// meydaScript.js
const audioContext = new AudioContext();
const htmlAudioElement = document.getElementById("audio");
const source = audioContext.createMediaElementSource(htmlAudioElement);
source.connect(audioContext.destination);
<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.7.0/p5.js"></script>     
        <script type="text/javascript" src="https://unpkg.com/meyda/dist/web/meyda.min.js"></script>
        <script src="main.js"></script>
    </head>
    <body>
        <main>
            <audio
                   controls
                   loop
                   crossorigin='anonymous'
                   id='audio'
                   src="assets/Ex2_sound1.wav"
                   >
            </audio>
            <br>
            <label for="level">Level</label>
            <input type="range"
                   id="levelRange"
                   name="level"
                   min="0.0"
                   max="1.0"
                   step="0.001"
                   />
        </main>
    </body>
    <script src="meydaScript.js"></script>
</html>

There is nothing in main.js for now, it is for adding some p5.js functionality later.
I’ve been scouring some posts online and in most cases, the solutions to the questions is just to add source.connect(audioContext.destination); I already have that, so what else am I missing? I’ve tried to console.log every single line in meydaScript.js, so I know my issue lies with createMediaElementSource or whatever it’s related to.

Redeclaration of “let MyClass” when defining an “enum” using an Object inside a JS class without class instantiation (no let is used)

I tried to define an “enum” using an Object and freeze inside a JS class in the next manner:

//test.js
class MyClass{
    static MyEnum = Object.freeze({
        kZero: 0,
        kOne: 1
    });
}

console.log(MyClass.MyEnum.kZero);
console.log(MyClass.MyEnum.kOne);

When running the html file in firefox I get the next output:

0                                          test.js:8:9
1                                          test.js:9:9
Uncaught SyntaxError: redeclaration of let MyClass
    <anonymous> file:<path>/test.js:1

Can someone please explain what’s wrong or direct me to a source where it’s explained? I read the related posts, but all I could find are cases when let is indeed used.

The html file:

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta charset="utf-8">
    <script src="test.js" charset="utf-8"></script>
    <link rel="stylesheet" href="test_styles.css"></link>    
    <title>Page</title>
</head>
<body>
    <script src="test.js"></script>
</body>
</html>

and the css file it empty.

Simplify any SVG path to create a solid black shape

Is it possible to transform any SVG into a solid black shape in an automated way (in javascript or otherwise) by simplifying the path?

Is there a library to do this, or is there another way?

Let’s take this SVG as an example:

enter image description here

<svg height="512" viewBox="0 0 16.933 16.933" width="512" xmlns="http://www.w3.org/2000/svg"><path d="M12.289 10.724a.265.265 0 0 0-.168.066 5.555 5.555 0 0 1-2.74 1.303.265.265 0 0 0-.2.363l1.597 3.806a.265.265 0 0 0 .489-.004l.732-1.825 1.852.743a.265.265 0 0 0 .342-.348l-1.653-3.942a.265.265 0 0 0-.251-.162zm-7.897.165-1.652 3.94a.265.265 0 0 0 .343.348l1.851-.744.732 1.825c.089.22.398.222.49.004l1.598-3.81a.265.265 0 0 0-.2-.363 5.556 5.556 0 0 1-2.743-1.297.265.265 0 0 0-.419.097z" fill="#ff5757"/><path d="M8.467.529C5.109.529 2.38 3.257 2.38 6.615s2.728 6.084 6.086 6.084 6.086-2.726 6.086-6.084S11.825.529 8.467.529z" fill="#ffcb3c"/><path d="M8.467 1.851a4.767 4.767 0 0 0-4.762 4.764c0 2.627 2.135 4.762 4.762 4.762s4.762-2.135 4.762-4.762A4.767 4.767 0 0 0 8.467 1.85z" fill="#ffea54"/><path d="M8.465 3.576a.265.265 0 0 0-.229.172l-.7 1.857-1.987.06a.265.265 0 0 0-.156.471L6.94 7.38l-.554 1.906a.265.265 0 0 0 .4.295l1.658-1.09 1.643 1.117a.265.265 0 0 0 .404-.289L9.97 7.402l1.568-1.215a.265.265 0 0 0-.148-.475L9.404 5.62l-.672-1.87a.265.265 0 0 0-.267-.175z" fill="#feaa2b"/></svg>

Here’s what I’d like to achieve:

enter image description here

<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 362.76 480.62"><g ><path d="m307.02,320.09C411.21,221.17,369.32,3.28,181.41,0-6.38,3.3-48.38,220.77,55.44,319.82l-47.2,112.57c-1.7,4.08.23,8.78,4.31,10.48.97,4.42,59.38-22.24,62.03-22.45l22.13,55.18c2.69,6.65,12.03,6.71,14.82.12l45.88-109.4c7.71.95,15.69,1.52,23.97,1.67,8.29-.14,16.28-.72,23.99-1.67,9.72,23.16,45.91,109.4,45.91,109.4,1.74,4.07,6.45,5.96,10.52,4.22,3.97,2.43,24.7-57.52,26.4-59.52l56,22.47c6.34,2.72,13.15-4.25,10.34-10.52-2.54-1.46-31.18-81.18-47.53-112.26Z"/></g></svg>

React not re-rendering

When i moved my code to a newer version of react for some reason its not rendering and updating ‘total votes’ when i click on any of the below buttons.

Edit: Also when i tried to print my data in the async functions, it comes up as null, but i checked my database and it does get updated.

Component below:

import { useState, useEffect } from "react"
import ProgressBar from "../ProgessBar"

const QuestionCard = ({ questionData, onDelete, supabase }) => {
  const [session, setSession] = useState(null);
  const [yes, setYes] = useState(questionData.votesYes);
  const [no, setNo] = useState(questionData.votesNo);
  //get user session
  useEffect(() => {
    supabase.auth.getSession().then(({ data: { session } }) => {
      setSession(session)
    })
    //watches for changes in session
    supabase.auth.onAuthStateChange((_event, session) => {
      setSession(session)
    })
  
  }, [])

  const handleDelete = async () => {
    const { data, error } = await supabase
      .from('questions')
      .delete()
      .eq('id', questionData.id)

    if (error) {
      console.log(error)
    }
    if (data) {
      console.log(data)
      onDelete(questionData.id)
    }
  }

  const handleYes = async () => {
    const { data, error } = await supabase
      .from('questions')
      .update({ votesYes: questionData.votesYes + 1, votesTotal: questionData.votesTotal + 1})
      .eq('id', questionData.id)
    if (error) {
      console.log('errored: ' + error);
    }
    if (data) {
      //sets data to update progress bar
      questionData.votesYes++;
      //sets yes hook state
      setYes(data[0].votesYes);
      
    }
    console.log('Votes Yes ' + data);
    console.log('Votes Yes Error ' + error);
  }

  const handleNo = async () => {
    const { data, error } = await supabase
      .from('questions')
      .update({ votesNo: questionData.votesNo + 1, votesTotal: questionData.votesTotal + 1})
      .eq('id', questionData.id)
    if (error) {
      console.log(error)
    }
    if (data) {
      //sets data to update progress bar
      questionData.votesNo++;
      //sets no hook state
      setNo(data[0].votesNo);
    }
  }
  const handlePollingResult = () => {
  }

  return (
    <div className="question-card">
      <h4>{questionData.question}</h4>
      <div className="polling-results">
        <h5>Total Votes: {yes + no}</h5>
      </div>
      <div><ProgressBar questionData={questionData}/></div>
      <div className="buttons">
        {!session ? <i>Please Sign in to vote</i> : <i className="yes-btn" onClick={handleYes}>Yes</i>}
        {!session ? <i></i> : <i className="no-btn" onClick={handleNo}>No</i>}
        {!session ? <i></i> : <i className="delete-btn" id='delete-btn' onClick={handleDelete}>delete</i>}
        {!session ? <i></i> : <i className="polling-result-btn" onClick={handlePollingResult}>Results data</i>}
      </div>
    </div>
  )
}

export default QuestionCard

When clicking on any of my buttons, i expected it to re-render the page and update the values, however it doesn’t seem to happen please let me know if you need more information, this is my first post 🙂

what wrong on scroll top functionality

Is this correct way to add scroll top functionality?

function toTop(){
  const topTrigger = document.querySelector('.back-to-top');

  topTrigger.addEventListener('click', () => {
    window.scrollTo({
      top: 0,
      left: 0,
      behavior: 'smooth',
    });
  });
}
toTop();

Does anyone have any experience switching from ffi-napi to koffi in an electron environment?

As we all know by now, ffi-napi is more or less just not supported in the latest versions of Electron (supposedly passed 20.0.0 from what I read) and I’m trying to find alternative packages to work on the latest build of Electron to read my dll file. I came across koffi and I was wondering if anyone had any experience with this package or have any recommendations of a ffi package to use on Electron (currently on 28.0.0). I read up on the documentation for koffi, but it doesn’t seem to be working. Errors wise, this is the error I’m getting when using ffi-napi and ffi-cross: (node:17688) UnhandledPromiseRejectionWarning: Error: External buffers are not allowed

Previous (Using ffi-napi outside of electron)

var ffi = require('ffi-napi');
const path = require('path');
const tlsClientLibrary = ffi.Library( path.join(__dirname, "..", "tls.dll"), {
    'request': ['string', ['string']],
    'getCookiesFromSession': ['string', ['string']],
    'addCookiesToSession': ['string', ['string']],
    'freeMemory': ["void", ['string']],
    'destroyAll': ['string', []],
    'destroySession': ['string', ['string']]
});

Within Electron

const koffi = require('koffi');
const tlsClientLibrary = koffi.load(path.join(__dirname, "..", "tls.dll"));
const request = tlsClientLibrary.func('request', 'str', ['str']);
const getCookiesFromSession = tlsClientLibrary.func('getCookiesFromSession', 'str', ['str']);
const addCookiesToSession = tlsClientLibrary.func('addCookiesToSession', 'str', ['str']);
const freeMemory = tlsClientLibrary.func('freeMemory', 'void', ['str']);
const destroyAll = tlsClientLibrary.func('destroyAll', 'str', []);
const destroySession = tlsClientLibrary.func('destroySession', 'str', ['str']);

Which tech stack should i learn java full stack or mern stack

I want to learn full stack development, should L learn java full-stack or go for MERN stack also it will be better if someone can share the industry trends among both and which would be better from job point of view

I researched about both and came to know that big projects or enterprise applications use java whereas startups prefer node.js

Navigating 12th Grade Studies and Coding Proficiency [closed]

I’m currently in the 12th standard and for the past three months, I’ve been learning HTML, CSS, and JavaScript. However, it’s crucial for me to shift my focus to my 12th-grade studies to avoid failing. The challenge is that my anxiety is preventing me from studying because I’m afraid I’ll forget the concepts of HTML, CSS, and JavaScript. How can I manage my time effectively to both study for my 12th-grade exams and continue gaining proficiency in HTML, CSS, and JavaScript?

i need to focus on both but i dont know how

generating a random number between min and max (inclusive) using JavaScript

I tried this function to find a random int number between two bonds, I know the method of Math.floor () and Math.random() how works, but I could not understand the logic with this function (max-min + 1) and the addition of min. why do we need to use (max-min+1) then the addition ofmin?

function random(min, max) {
    const num = Math.floor(Math.random() * (max - min + 1)) + min;
    return num;
}

console.log(random(5, 10));