Unable to send objects as payload data while making an Fetch API request

I have a react frontend and node backend, I am fetching a list of objects from an external API using Axios and then trying to pass it to my node backend. The issue is that the node backend is not able to receive this payload data on the backend, req.body returns an empty object.
To debug, I’ve seen what happens in the network tab, and have observed that the payload data just returns the data type instead of the actual data as shown below.

enter image description here
Here is what my front-end code looks like:

let faqlist = "";
// fetching data from one api
await axiosinstance
  .get(
    "https://linktotheapi/api/faq"
  )
  .then((res) => {
    faqlist = res.data;

    console.log("This is faqlist", faqlist);
    console.log(typeof faqlist);
    // passing the data fetched from 1st api to node/express backend.
    fetch("/create-page", {
      method: "POST",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json",
      },
      body: faqlist,
    });
    
  });

}

How can i return only the value with mongoose populate?

I’m using mongoose-paginate-v2 and also i’m using populate. It works but when i populate my field, the population returns an array and i want to put the name of the value inside of the field cajaID:

What i want to get:

{
    "_id": "5aa23958-06a9-4ff1-b614-d112d81b2eSi",
    "nombre": "Zone",
    "cajaID": "Caja grande"
}

What i get:

{
    "_id": "5aa23958-06a9-4ff1-b614-d112d81b2eSi",
    "nombre": "Zone",
    "cajaID": {
        "nombre": "Caja grande"
    }
}

My code:

await ZonesModel.paginate(query, { populate: {path: 'cajaID', select: { '_id': 0,'nombre':1}}}, function(err, doc) {

    if (err) {
        error = new Error(err);
        error.status = 500;
        throw error;
    }
    
    data = doc;
})

mongoose-paginate-v2 also has projection but when i want to access to the field “nombre” it doesn’t work, just returns the value of the field which has the id of the another collection.

await model.paginate(query, { populate: {path: 'cajaID', select: { '_id': 0,'nombre':1}}, projection: {  caja: "$cajaID" }}, function(err, doc) {

    if (err) {
        error = new Error(err);
        error.status = 500;
        throw error;
    }
    
    data = doc;
})

This code return this:

{
    "_id": "5aa23958-06a9-4ff1-b614-d112d81b2eSi",
    "nombre": "Zone",
    "cajaID": {
        "nombre": "Caja grande"
    },
    "caja": "5aa23958-06a9-4ff1-b614-d112d81b2eBa" // id of the another collection but i can't access to the nombre field
}

Quiz using HTML, CSS & JS [closed]

I’m creating a quiz using HTML, CSS, and JS. The overall layout of the quiz is that it opens with the title, instructions, and Start button. Upon clicking start, you’re given the first question and 4 answer options (which are buttons themselves). Clicking an option makes the feedback appear below the last option and updates the question with a new one and answer options with new ones. In HTML, should I create only the intro container (containing title, instruction text, and Start button) and use that as the template for the questions?
Please suggest how I should go about this. Thanks!

Here’s my HTML so far. Would this work or should I remove the second & third divs?

<body>
    <header class="score-time">
        <a href="./highscores.html">View high scores</a>
        <p>Time:</p>
    </header>
    <main class="main-content">
        <div class="intro">
            <h1 class="title">
                Coding Quiz Challenge
            </h1>
            <p class="instructions">
                Try to answer the following code-related questions within the time limit. <br /> Keep in mind that incorrect answers will penalize your score/time by ten seconds.
            </p>
            <button class="start-btn" id="start-quiz" type="button">Start Quiz</button>
        </div>
        <div id="questions" class="hide">
            <h2>Question</h2>
            <button>Option 1</button>
            <button>Option 2</button>
            <button>Option 3</button>
            <button>Option 4</button>
        </div>
        <div id="results" class="hide">
            <h2>All done!</h2>
            <p>Your final score is</p>
            <label for="initials">Enter your initials:</label>
            <input type="text" id="initials">
            <button class="submit-btn" id="submit-initials" type="submit">Submit</button>
        </div>
    </main>
    <script src="./assets/js/script.js"></script>   
</body>

how do I destructure this object Array? [duplicate]

I have a fetch request that I’m handling it returns an object And I just can’t seem to destructure it.

enter image description here

the value that I’m trying to get is 0 > meanigs> definition

I’ve tried to map it out so I can get the value but nothing works

I have it stored in a variable called data, and every time I try data. meanings it doesn’t filter the object any further.

I just want a way to filter that definition variable

written for each function isnt a function

Im having an issue where the function is not being recognized as a function and throwing a console error.

Error: “Uncaught TypeError: choices.forEach is not a function”

Here is the function in question:

    choices.forEach(choice => {
        choice.addEventListener('click', e => {
            if (!acceptingAnswers) return

            acceptingAnswers = false
            const selectedChoice = e.target
            const selectedAnswer = selectedChoice.dataset['number']


            let classToApply = selectedAnswer == currentQuestion.answer ? 'correct' : 'incorrect'
            //if answer is correct add 100 to score
            if (classToApply === 'correct') {
                incrementScore(SCORE_POINTS)
            }

            selectedChoice.parentElement.classList.add(classToApply)

            setTimeout(() => {
                  selectedChoice.parentElement.classList.remove(classToApply)
                  getNewQuestion();
            }, 1000)
         })
    }); 

I don’t know how much code I should add to provide full context, so please let me know if additional code is required and ill make the edits right away.

Thanks, dhuw

Cannot access function in express for pub sub cloud function

I am trying to use cloud functions to do a pub sub cloud scheduled function in nodjs but I am having difficulty calling the function because every time I compile the code I get this error

Error: Failed to load function definition from source: Failed to generate manifest from function source: ReferenceError: Cannot access 'sendNotifications' before initialization

what is the correct way I am meant to add the send notification function into my pub sub scheduler

// The Cloud Functions for Firebase SDK to create Cloud Functions and set up triggers.
const functions = require('firebase-functions');
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cors = require('cors');
const errorHandler = require('./_middleware/error-handler');
// The Firebase Admin SDK to access Firestore.
const admin = require('firebase-admin');
admin.initializeApp();
const sendNotifications = require('./notifications.controller')


// Create an Express object and routes (in order)
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(cookieParser());
// allow cors requests from any origin 
app.use(cors());
// api routes
app.use('/', require('./invites.controller'));
app.use('/', require('.//payments.controller'));

// INVITE PAGE
app.get('/invite/:inviteId', function(request, response) {
  response.sendFile(__dirname +  '/download.html');
});

// global error handler
app.use(errorHandler);
// Set our GCF handler to our Express app.
exports.invites = functions.region('europe-west2').https.onRequest(app);
exports.payments = functions.region('europe-west2').https.onRequest(app);
exports.notificationScheduler = functions.pubsub
  .schedule('0 8 * * *')
  .timeZone('Europe/London')
  .onRun(async() => {
    await sendNotifications()
  });

How to replace name with regex [duplicate]

I’m trying to replace %username% with any name inputted. I wanna replace that keeping the end part of the entire string %username%, your Account Has Been Successfully Created!

<h2 class="done">%username%, your Account Has Been Successfully Created!</h2>
let name = $(".done");
name.text().replace(/%(.+?)%/, this.value);

this.value is just the username inputted in the input field.

Sequelize TypeError: Cannot read properties of undefined (reading ‘split’)

I am trying to update a sequelize model partially that contains a string array value separated by semicolons.

languages: {
      type: Sequelize.STRING,
      allowNull: false,
      get() {
        if (this.getDataValue('languages') === null) {
          return [];
        } else {
          return this.getDataValue('languages').split(';');
        }
      },
      set(val) {
        if (val.length === 0) {
          this.setDataValue('languages', null);
        } else {
          this.setDataValue('languages', val.join(';'));
        }
      },
    },

Keep EventListener running untill the box is checked

The Context

I have a form where text fields must pass validation before the checkbox to accept terms and conditions is shown.

The Problem

I want the code to hide the element, even after validation has passed temporarily, for example, if a user changes the text in an input field to subsequently fail validation.

Currently

I have been successful so far in getting the checkbox to be hidden until validation has passed with:

form.addEventListener("input", function(){
    eval();
    if (evalResult === true) {
        showBox();
    } else {
        hideBox();
    }
});

where showBox and hideBox use object.style.visibility to hide the respective DOM element.

The eval() function does the validation and returns a boolean to the evalResult variable.

However

If a user changes the text in an input field, after showBox has been called, the check box remains visible.
The issue with this, is that invalidated data may be sent to the server.

Some research shows that a loop may be the answer, but I can’t have the loop running out.

Would this be a case for using a debounce()? I think that might unfortunately be a bit beyond my knowledge at the moment.

All help will be greatly appreciated.

Edit

If there is a way to keep the handler running until the checkbox is checked?

promise.all cause trigger to be fired only once

I’m confused as to why this happen, because to my understanding a before insert trigger will get fired for every new row, which do work when I run the code synchronously. But because my data can be quite a lot, I’m trying to make it asynchronous.

For example, I tried to insert two transaction headers which should fire the trigger twice to generate each transaction number, but it only generate one number for both rows.

enter image description here

Below is my trigger code :

CREATE DEFINER=root@% TRIGGER generate_transaction_number BEFORE
INSERT ON transaction FOR EACH ROW BEGIN DECLARE
v_max_transaction_num VARCHAR(17); DECLARE v_separator VARCHAR(1)
DEFAULT ‘/’; SELECT MAX(transaction_number) INTO
v_max_transaction_num from transaction t WHERE
DATE(t.transaction_date) = CURDATE();

IF(v_max_transaction_num IS NULL OR v_max_transaction_num = ”) THEN
SET v_max_transaction_num = ‘0’; END IF;

SET new.transaction_number = concat(‘INV’, v_separator,
DATE_FORMAT(CURDATE(),’%Y%m%d’), v_separator,
LPAD(SUBSTRING_INDEX(v_max_transaction_num,v_separator,-1)+1,4,’0′));
END

Below is the javascript async code :

let promises = [];

for (const transactionHeader of transactionHeaders){
promises.push(mTransactions.addTransaction(transactionHeader)); }

await Promise.allSettled(promises);

My goal is to make it asynchronous, but and make the trigger fired for every row.

ReactJS Array Parse inside Object

I have a object

{
    "id": 1,
    "collectionName": "dsa",
    "collectionItemsID": [
        "ad",
        "deneme1"
    ],
    "ownerOfCollection": "117961395738439786389",
    "createdAt": "2022-06-16T12:54:52.146Z",
    "updatedAt": "2022-06-16T12:54:52.146Z"
}

When I push to front like that in ReactJS

{collection.collectionItemsID}

I am getting output with joined.

addeneme1

I want to push object collectionItemsID and push to front with

<a href=/{collectionItemsID}>  >> Like that

It needs to be seperated. I didnt wanted to use javascript for seperate. I need to learn how to do correctly. I think I needs to use Object.keys but I am failed with this way.

How to measure total memory used by a single function

I wonder how to measure total memory used by the function in JavaScript. I found that there is an API performance.memory. I have noticed that usedJSHeapSize is not only for the single page but can also share summary between other tabs. Let’s assume that in my case, I have always opened only one tab, so I should measure memory of only this one tab I am interested in. I also read that I should wait some time after function execution to let garbage collector clear all unused memory. In the end, I came up with below a solution, but I do not know is it a good idea and is the way how I measure memory correct. If you have any thoughts about that, let me know please.

function wait(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

function fun1() {
  // function logic...
}

function fun2() {
  // function logic...
}


function measureMemory(functionToMeasure) {
  const memoryStart = performance.memory.usedJSHeapSize;
  functionToMeasure();
  const memoryEnd = performance.memory.usedJSHeapSize;
  return memoryEnd - memoryStart;
}


async function runBenchmark() {
  const totalMemoryUsedByFun1 = measureMemory(fun1);
  // I wait 2min to be sure garbage collector clean all unused memory
  await wait(120000);
  const totalMemoryUsedByFun2 = measureMemory(fun2);
}

What do you think, is it a good approach/idea of measuring memory used by function? Does 2min is enough time for garbage-collector to clear unused memory?

I also have seen that there is such API measureUserAgentSpecificMemory(), but I think this API is not working at all even after turning on #experimental-web-platform-features

How to hook into html with my own html overlay?

I am trying to overlay some HTML code over a website’s image using <iframe> and CSS.

The website is a weather-monitoring website (which we’ve purchase btw), that I want to overlay with my own HTML code and image.

Is it possible to “hook” into one portion of the image with my own image? I want it hooked (so-to-speak, pardon my jargon), so the browser’s resizing won’t change it’s layout and for it to also work on mobile device browsers.

This is the website I am referring to (sorry it’s not a public accessible site).

3rd party weather monitoring website

I’ve managed to somewhat achieve what I want using this code…

<style>
  iframe {
    position: absolute;
    border: none;
    box-sizing: border-box;
    width: 100%;
    height: 100%;
  }
</style>

<div style="z-index:99;position:absolute;top:115px;right:352px">
    <canvas id="compass" height="230" width="230"></canvas>
    <asp:Label ID="lblDegrees" runat="server"></asp:Label>
</div>

<iframe id="iframe1" 
    src="https://asdjkhsdfjkhsdfjkh">    <-- internal website for above image
</iframe>

But as you’ve guessed, the top and right positioning is hardcoded to overlay that box in the right spot.

However, as soon as I re-size the browser or view it on a mobile device, the <canvas> element shifts to the right (or left or down) and the underlying compass dial shows from behind (somewhat partially obscured).

i.e.

enter image description here

There must be a better way to do this. Any ideas and suggestions?

Thanks

Run function when global variable is updated lua

Hello I have a lua global variable used as a settings config made of a list of arrays. I have buttons that visually update when clicked, updating a section of an array. There are other ways to change the settings besides clicking however, but I am not sure how to get the visual effects to indicate which settings have been changed when that is done as the function to update the “state” is not called.

ex of global variable

getgenv().config = {
visual = {
    1 = false,
    2 = false,
},
audio = {
    a = false,
    b = false,
}
}

ex of physical button

audio:CreateToggle("mute sound", nil, function(State) config.audio.a = State end)

state function

local function SetState(State)
    if State then
            Toggle.Toggle.BackgroundColor3 = Config.Color
        elseif not State then
            Toggle.Toggle.BackgroundColor3 = Color3.fromRGB(50,50,50)
        end
    ToggleState = State
    Callback(State)
end

Is there an easy way I can make sure that the the button is in the right state if the array is updated weather it was clicked or not?