Node js How to make changes to an exported module so it will be shown in other files

I am following a course for a Node js ( among other things ) , in this course passport.js is used. In index.js file i required the configuration module that we created for passport.js to use “Google Strategy” , and in my routes i required the global instance for passport.js and i used it to authenticate user via oauth of google .
my question is how the passport code in my routes knows that i am using google strategy and their configs like ClientID and ClientSecret even if i am not using the same instance of passport.js in my config file , to make things clear here is the code :

Index.js

const express = require("express");
require("./services/passport");


const app = express();

require("./routes/authRoutes")(app);

app.listen(5000);

passport.js inside my services folder

const passport = require("passport");
const GoogleStrategy = require("passport-google-oauth20").Strategy;
const keys = require("../config/keys");

passport.use(
  new GoogleStrategy(
    {
      clientID: keys.googleClientID,
      clientSecret: keys.googleClientSecret,
      callbackURL: "/auth/google/callback",
    },
    (accessToken, refreshToken, profile, done) => {
      console.log("accessToken", accessToken);
      console.log("refreshToken", refreshToken);
      console.log("profile", profile);
      console.log("done", done);
    }
  )
);

authRoute.js

const passport = require("passport");
// here i am importing the global passport , how this instance knows that i used google strategy
// in my configs and their configs like googleClientID ...ect ?

module.exports = (app) => {

  app.get(
    "/auth/google",
    passport.authenticate("google", {
      scope: ["profile", "email"],
    })
  );

  app.get("/auth/google/callback", passport.authenticate("google"));
};


playstate only runs once

im trying to make the animation play whenever someone clicks a link. now when you do that the first time it works on the sections and the main div. but when you click another link the main div doesnt play the animation but the sections do.
so what im trying to do is get the animation to play when i click a link.

this is my code:

*{
    margin: 0px;
    padding: 0px;
}
html{
    font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
    background-image: url('/move_heart.gif');
}
body{

}
.container{
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100vh;
}
.flexrow{
    display: flex;
    flex-direction: row;
}
.flexrow a{
    margin: 5px;
}
main{
    border: 1px solid black;
    background: white;
    border-radius: 10px;
    padding: 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: all 1s;
    transition: padding 1.5s;
    width: 200px;
    margin: 10px;
}
main img{
    border-radius: 50%;
    transition: border-radius 0.5s ;
}
main img:hover{
    border-radius: 20%;
    transition: border-radius 0.5s ;
}
section{
    border: 1px solid black;
    background: white;
    border-radius: 10px;
    padding: 30px;
    display: flex;
    flex-direction: column;
    align-items: center;
    transition: all 1s;
    transition: padding 1.5s;
    display: none;
    width: 200px;
    margin: 10px;
}
.main .info{
    text-align: right;
    margin-left: 5px;
}
a{
    text-decoration: none;
    color: black;
    transition: all 1s;
}
a:hover{
    text-decoration: solid underline;
}
.popper{
    animation: popin 1s;
}
.downer{
    animation: updown 1s;
}
@keyframes popin {
    0%{
        transform: scale(0.9);
    }
    25%{
        transform: scale(1.1);
    }
    50%{
        transform: scale(0.9);
    }
    100%{
        transform: scale(1);
    }
}
@keyframes updown {
    0%{
        transform: translateY(0px);
    }
    50%{
        transform: translateY(20px);
    }
    100%{
        transform: translateY(0px);
    }
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/style.css">
</head>
<body>
    <div class="container">
        <main class="main" id="main">
            <div class="musicPlayer">

            </div>
            <div class="flexrow">
                <img src="/7499F638-159C-4954-A18A-F59BE1116F96.jpg" height="100" alt="">
                <div class="info">
                    <h3>name</h3>
                    <h4>age</h4>
                    <h4>etc</h4>
                </div>
            </div>
            <div class="flexrow">
                <a class="about">about</a>
                <a class="dni">dni</a>
                <a class="other">other</a>
                <a class="other2">other</a>
            </div>
        </main>
        <section id="about">text</section>
        <section id="dni">text</section>
        <section id="other">text</section>
        <section id="other2">text</section>
    </div>
<script>

links = document.querySelectorAll("a")
parts = document.querySelectorAll("section")
    links.forEach(element => {
        element.addEventListener("click", function(){
            var selected = element.className;
            parts.forEach(element =>{
            element.style.display = "none";
        })
            console.log(selected)
            document.getElementById(selected).style.display = "block";
            document.getElementById("main").className = "downer";
            document.getElementById(selected).className = "popper";
            document.getElementById("main").style.animationPlayState = "running";
            document.getElementById(selected).style.animationPlayState = "running";
        })
    });



</script>
</body>
</html>

Function step by step in one Click in react

I use ReacJs and Redux in my project and have a sitoation where i need to click only one time and function have to run 2 inside functions step by step. 2nd function cant run before ended func2. How can I do this function only in one click on mainfunc()? Need a example code please.

func1()

func2()

mainfunc(){
 func1()
 func2()
}

Ajax sends data like data[accountnumber]

Im getting an error with my ajax request. The api should be correct so i don’t know what i’m doing wrong here.

Network tab: enter image description here

And this is the code:
enter image description here

I have a feeling that the way data is submitted(inside boxes?) could be the issue here. Any ideas?

The program not change music all time

I would like create a program, loop the music, on my iframe.

Code html & javascript:

<html>
<body>
<form id="form1" runat="server">
    <div id="wrapper">
        <div id="first">

            <div class="div1" id="">
                <iframe id="player" src="https://www.youtube.com/embed/DjB1OvEYMhY?enablejsapi=1&autoplay=1" style="margin-top: 5%; margin-left: 5%;" width="750px" height="345"></iframe>
            
    </div></div>
    <script>
        var player;
        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                events: { 'onStateChange': onPlayerStateChange }
            });
        }
        function onPlayerStateChange(event) {
            switch (event.data) {
                case 0:
                    console.log('video ended');
                    jQuery.ajax({
                        method: "POST",
                        url: "WebForm1.aspx/returnid",
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        data: JSON.stringify({ subject: document.getElementById("player").src, message: "message", messageId: 1, pupilId: 1 }),
                        error: function (XMLHttpRequest, textStatus, errorThrown) {
                            console.log("Error", errorThrown);
                        },
                        success: function (result) {
                            console.log("success", result);
                            document.getElementById("player").src = "https://www.youtube.com/embed/" + result.d + "?enablejsapi=1&autoplay=1";
                            document.getElementById("player").addEventListener("onStateChange", window.onPlayerStateChange);
                            /*document.getElementById("player").events: {
                                onStateChange: window.onPlayerStateChange
                            }*/
                        }
                    });

                    break;
                case 1:
                    console.log('video playing from ' + player.getCurrentTime());
                    break;
                case 2:
                    console.log('video paused at ' + player.getCurrentTime());
            }
        }
        function record(str) {
        }
    </script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://www.youtube.com/iframe_api"></script>
</form>

Code c#:

[WebMethod]//[WebMethod()]
    public static string returnid(string subject, string message, string messageId, string pupilId)
    {
        Console.WriteLine("testar");
        try
        {
            SqlConnection liga = new SqlConnection(@"Server=(localdb)MSSQLLocalDB; DataBase=Twitch; Integrated Security=True");
            SqlCommand command = new SqlCommand();
            SqlDataReader dr;
            subject = subject.Replace("https://www.youtube.com/embed/", "").Replace("enablejsapi=1&autoplay=1", "");
            command.Connection = liga;
            
                liga.Open();
                command.CommandText = $"delete from tblMusicsRedeem where urlMusic = '{subject}'";
                dr = command.ExecuteReader();

                liga.Close();
            
            liga.Open();
            command.CommandText = $"select* from tblMusicsRedeem where RequestA < '{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}'";
            dr = command.ExecuteReader();
            string urlMusic = "";
            while (dr.Read())
            {
                if (urlMusic == "")
                {
                    urlMusic = dr["urlMusic"].ToString();
                    break;
                }
            }
            return urlMusic;
        }
        catch (Exception ex)
        {

        }
        Console.WriteLine("testar");

        return "";//https://www.youtube.com/watch?v=8elyZ6aGgZY
    }

The problem on this project is. Play 1 music automatic, but second time he dont change the music and dont play the other music. My question is why? On Sql, urlMusic have this string (uaQSMzbvjyA, GhRDtCQBL5Q, uaQSMzbvjyA, nQii-MkTfQw).

I think the problem is on javascript, not in sql, c# or html.

Scaling a div inside scrollable container

I have a scrollable container inside which I have an element that overflows and causes the scroll.

I want to zoom the whole div. Transform origin is set to 0 0 because I need to be able to scroll it and for some reason HTML doesn’t allow that when it’s 50% 50%.

Everything works correctly when the element is not scrolled down. However, when I scroll, the transform origin is still set to the top left point all the way up. Causing the scroll to go back to it resulting in a weird scroll that doesn’t scroll where I want.

How can I work around this?

Codesandbox here:
https://codesandbox.io/s/vigilant-butterfly-i5klyx?file=/index.html

How do I solve this formik onSubmit error with Typescript?

for some reason I’m getting an error on onSubmit prop of Formik:

Type ‘(values: { email: string; password: string; }) => { type:
string; payload: { email: string | null; password: string | null; };
}’ is not assignable to type ‘((values: { email: string; password:
string; }

These are the Formik props:

<Formik
                    initialValues={{ email: '', password: ''}}
                    validationSchema = { LoginSchema }
                    validateOnChange={false}
                    onSubmit={ (values) => requestLogin(values.email, values.password)}
                >

And this is requestLogin action:

export const requestLogin = (email: string, password: string) => ({
type: types.AUTH_USER,
payload: {
    email: email || null,
    password: password || null
}

});

Everything should be fine since requestLogin takes 2 parameters of type ‘string’ or am I missing something here?

how to write a button that will empty the colored grid

i am making a simple etch a sketch. so far the grid will fill with color when you hover a mouse over it.
i am trying to create a button with a function that clears the grid of color when clicked. maybe by clearing the class that will toggle when the mouse hovers over the grid

.banner {
display: flex;
justify-content: center;
}

.container {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
margin: 0 0 2em 0;
}

.grid {
display: grid;
grid-template-columns: repeat(16, 1fr);
 }

 .box {
height: 20px;
width: 20px;
border: 1px solid rgb(122, 121, 121);
background-color: lightgray;
 }

 .box:hover { cursor: pointer; }
 .box:hover:not(.filled) { background-color: 
 rgb(151, 179, 195); opacity: 0.3; }

 .filled { background-color: black; }

.buttoncontainer{
display: flex;
gap: 10px;
justify-content: center;
}


const grid = document.querySelector('.grid');
  grid.addEventListener('mouseover', handleClick);

  const clear = 
  document.querySelector('.clearbutton')
  clear.addEventListener('click', clearGrid);

  function getGrid(gridNumber) {
 for (let i = 1; i <= gridNumber * gridNumber; i++) {
const box = document.createElement('div');
box.classList.add('box');
grid.appendChild(box);
   }
  }

   getGrid(16);


  function handleClick(e) {
    if (e.target.matches('.box')) {
   e.target.classList.toggle('filled');
   }
    }

   function clearGrid(

   )

How to access console logs from the url in ios (Swift) – WKWebview

I have tried the following process
if let url = URL(string: urlString) {
            webViewForTheCard.load(URLRequest(url: url))
        }

let contentController = WKUserContentController()
let source = “function captureLog(msg) { window.webkit.messageHandlers.logHandler.postMessage(msg); } window.console.log = captureLog;”
let script = WKUserScript(source: source, injectionTime: .atDocumentEnd, forMainFrameOnly: false)
webViewForTheCard.configuration.userContentController.addUserScript(script)
webViewForTheCard.configuration.userContentController.add(self, name: ReactNativeWebView)

        contentController.add(self, name:ReactNativeWebView)
        
        let config = WKWebViewConfiguration()
        config.userContentController = contentController
        
        self.webViewForTheCard = WKWebView(
            frame: self.webViewForTheCard.bounds,
            configuration: config
        )
        
        //self.webViewForTheCard = WKWebView( frame: self.containerView!.bounds, configuration: config)
        self.view = self.webViewForTheCard


but this does not work.

page.addScriptTag() causing server errors and alarms

I’m making a bot that could go though my clients website and get details for the products they have and since the products’ pricing, availability, promos & etc. changes multiple times in a week then I need to update my spreadsheet too manually for the rest of my team to use. Finding those changes for each product is my job which is very prone to error. If only they could provide me with an API, life would have much been easier but no.

My client told me that I’ve been spamming their error report and tripping their alarms on their server error logs and the functions/files they found are the helper functions that I injected into the DOMWorld on their site using page.addScriptTag('./client/helper.js') and the helper functions inside that file (wasn’t sure if that is all they found but so far they have only mentioned that file and the functions inside it).

    const product_name = await page.$eval('#product-name', product => {
         getProductName(product )
    })

The getProductName() function comes from this file ./client/helper.js.

    //This simply removes unwanted characters
    function getProductName(product ) {
        return product.innerHTML.replace(/[s]{2}/g,'')
    }

I wasn’t aware that they could see this as I thought puppeteer runs locally on the client-side, on my computer only.

I have few ideas that could make this go undetected and silence their alarms and errors.
First would be to NOT use page.addScriptTag('./client/helper.js') at all and put the codes of this file straight into the main file then do further processes after getting the innerHTML.

    const product_name = await page.$eval('#product-name', product => {
         return product.innerHTML
    })

    const final_product_name = product_name.replace(/[s]{2}/g,'')

This does work but my only concerns is if will this still be detectable as I am still running an anonymous function inside page.$eval(). That I am still trying to find out if my client complains again.

So my question really is..

  1. Will removing page.addScriptTag() and using anonymous function be undetectable?
  2. is there any other way to scrape string in the DOMWorld ? (if it turns out that anonymous function still triggers errors)
  3. Is this because i’m using headless chrome?

Thank you for reading.

Vue.js and Jest Not able to find any elements with wrapper.find(..)

I have this component that I’m using as popup:

<template>
<full-screen-popup ref="popup">
  <div class="confirm-dialogue-container">
    <div class="dialog-header">
      <h1 id="confirm-title-lbl">{{ title }}</h1>
      <h2 id="confirm-message-lbl">{{ message }}</h2>
    </div>
    <div class="actions-container">
        <button id="bt-confirm-delete" class="btn-action primary" @click="_confirm">{{ confirmLblButton }}</button>
        <button id="bt-cancel-delete" class="btn-action " @click="_cancel">{{ cancelLblButton }}</button>
    </div>
  </div>
</full-screen-popup>
<script>
import FullScreenPopup from './FullScreenPopup.vue'

export default {
  name: 'ReplaceDialogue',
  components: { FullScreenPopup },
  data: () => ({
    title: undefined,
    message: undefined,
    confirmLblButton: undefined,
    cancelLblButton: undefined,
    resolvePromise: undefined,
    rejectPromise: undefined
  }),
  methods: {
    show (opts = {}) {
      this.title = opts.title
      this.message = opts.message
      this.confirmLblButton = opts.confirmLblButton
      if (opts.cancelLblButton) {
        this.cancelLblButton = opts.cancelLblButton
      }
     
      this.$refs.popup.open()
      // Return promise so the caller can get results
      return new Promise((resolve, reject) => {
        this.resolvePromise = resolve
        this.rejectPromise = reject
      })
    },

    _confirm () {
      this.$refs.popup.close()
      this.resolvePromise(true)
    },

    _cancel () {
      this.$refs.popup.close()
      this.resolvePromise(false)
    }
  }
}
</script>


<template>
    <transition name="fade">
        <div class="full-screen-popup" v-if="isVisible">
            <slot></slot>
        </div>
    </transition>
</template>

<script>
export default {
  name: 'FullScreenPopup',
  data: () => ({
    isVisible: false
  }),
  methods: {
    open () {
      this.isVisible = true
    },
    close () {
      this.isVisible = false
    }
  }
}
</script>

Now, I would like to write some unit tests about for this component:

  it('Test', () => {
    
    const wrapper = mount(ReplaceDialogue)
            
    const promise = wrapper.vm.show({
        title: popupTitle,
        message: popupMessage,
        confirmLblButton: confirmButton,
        cancelLblButton: cancelButton
    })  

    let x = wrapper.find('#confirm-title-lbl')
    
  })

Seams that the html is empty. I’m not able to found any element with the wrapper.find(..)
Any suggestions?

get data from async function to another function React JS

I have problem with async function. I need track.user in another function but my func getTracks() async. I don’t have clue how can i get this.

const Player = ({trackUrl, index, cover, id}) => {
    const [track, setTrack] = useState({})
    const [user, setUser] = useState({})

    useEffect(() => {
        const getTracks = async () => {
            await httpClient.get(`/track/${id}`)
                .then((response) => {
                    setTrack(response.data);
                })
        }
        getTracks();
        getUser() // track.user undefined 
    }, [])

    const getUser = async() => {
        await httpClient.get(`/profile/${track.user}/`)
            .then((response) => {
                setUser(response.data);
            })
    }
}

Send token from owner account from nodejs backend (Custom ERC20 token)

I made a smart contract for token on the Polygon network. The server part is NodeJS.

Now I’m trying to implement the functionality of sending tokens to the recipient’s wallet from the token creator’s wallet.

The transfer method in the contract is simply taken from OpenZeppelin’s ERC20 contract.

    /**
     * @dev See {IERC20-transfer}.
     *
     * Requirements:
     *
     * - `to` cannot be the zero address.
     * - the caller must have a balance of at least `amount`.
     */
    function transfer(address to, uint256 amount) public virtual override returns (bool) {
        address owner = _msgSender();
        _transfer(owner, to, amount);
        return true;
    }

Calling the contract method from the server looks like this:

const web3Instance = new web3('providerUrl');
const tokenSmartContract = new this.web3Instance.eth.Contract(TokenABI, 'tokenAddress');

async sendTokenToWallet(amount, wallet) {
   await this.tokenSmartContract.methods.transfer(wallet, amount).send();
}

But no transfer happens.
I know I need to use the sender’s private key somewhere, but I can’t figure out where.

n.compareDocumentPosition is not a function

I’m trying to create a personal web, but there is a problem when using next.js, namely when pressing the hamburger button and the fan button then it displays an error message: n.compareDocumentPosition is not a function.

I am confused about this problem because when I run it locally there is no problem.

can anyone help me?

You can see the error message in the console from the following web link: Website Link

this is when i press the humberger button

the following when I press the fan button, it gets stuck while loading