Remove query string parameter If it undefined

I’m New to Node.js, I’m trying to implement the search functionality, I need a optional parameters to be passed, So for example I should be giving both

http://localhost:8080/getData?userName=John Smith 

or

http://localhost:8080/getData?&userId=1 

or

http://localhost:8080/getData?userName=John Smith&userId=1

But If I try to implement the below code I am getting url like this

Request URL: http://localhost:8080/getauditlogs?userName=John%20Smith&userId=undefined

Json data

let mockData={
"mockDa":
[
    {
        "userId":"2",
        "userName":"Dave steve",
    },
    {
        "userId":"1",
        "userName":"John Smith",
    }
],
};

Code :

app.get('/getData', (req, res) => {
  if (req.headers.authorization) {
  let re = mockData.mockDa;
  let userName = req.query.userName;
  let userId = req.query.userId;
    let filterData = re.filter((data) => {
      return data.userId === userId && data.userName === userName
    }
    )
    console.log(filterData)
    const response = {
      header: getSuccessHeader,
      body: filterData
    };
    res.status(200);
    res.send(response);
});

math.abs in terms of parameter/ closest values

how to make math. Abs work on parameters to determine closest values to a randomly generated number?
I have looked at the function created with three parameters namely human guess, computer guess and secret number to be created but i cant see to work around math. Abs at the moment ? any help and it is for a number guesser game

Losing props in react native when navigating backwards

I have a simple problem: I have a parent component that navigates to a child component, the child component is supposed to update the state on the parent component when the child navigates backwards (this.props.navigation.navigate("parentComponent", { params }) ). According to the docs this should be easy: https://reactnavigation.org/docs/params/

The navigation action is treated like a goBack action if the screen already exists. However when I do this and try to console.log the props in the parents screen after going back it shows it as empty.

Parent.js

 <View style={styles.availabilitycontainer} visible={true}>
          <View style={styles.titlegroupcontainer}>
            <Text style={styles.abouttitle}>Schedule Availability</Text>
            {/*Redirect to edit schedule*/} 
            <TouchableOpacity
              style={styles.cameracantainer}
              onPress={() =>
                this.props.navigation.navigate("ChildComponent")
              }
            >
              <Image source={Editoutline} />
            </TouchableOpacity>
          </View>

          <ProfileAvalability />
        </View>

Child.js

async submitToBackend(){
    /* Code to submit to backend omitted */
  this.props.navigation.navigate('ParentComponent', { params });
}

Unable to capture the closest span element on mouse click

The MDN specification of the closest method reads that the method traverses the DOM upwards, in the direction to the document root. But what method does one need to use in my case instead of closest then?

In my HTML page I have the following code:

<div class="slider__steps">
  <span></span>
  <span></span>
  <span class="slider__step-active"></span>
  <span></span>
  <span></span>
</div>

In my JS file I want to capture the closest span element to a mouse click and change its CSS class. I try to do this as follows:

moveSlider(elem) {
    let sliderSteps = elem.querySelector('.slider__steps');
    let spans = sliderSteps.querySelectorAll('span');
    elem.addEventListener('click', moveThumb);
    function moveThumb(event) {
      for (let span of spans) {
        span.classList.remove('slider__step-active');
      }
      event.target.closest('span').classList.add('slider__step-active');
    }
  }

But the error I get is

Uncaught TypeError: event.target.closest(…) is null

How does one actually catch these spans on mouse clicks?

AwaitingReactions is practically not working on mine. Discord.js

I dont know why but i followed the guide in discord.js about awaiting reactions but it seems it doesnt work on mine. I dont know why. Whenever i hit the emoji it doesnt collect it. I pretty much goes to every answered question here in stackoverflow but i still cannot fix it.

const { Client, Message, MessageEmbed } = require("discord.js");

module.exports = {
  name: "error",
  /**
   * @param {Client} client
   * @param {Message} message
   * @param {String[]} args
   */
  run: async (client, message, args) => {
    message.delete({ timeout:2000 })
    var randstr = Math.random().toString(36).replace(/[^a-z]+/g, '').substr(0, 5);
    var randnum = Math.floor(Math.random() * 100);
    var comb = randstr + randnum;
    var sayEmbed = new MessageEmbed()
        .setTitle('Console Error #'+ '`' + comb + '`' + ' sent by ' + message.member.user.tag)
        .setDescription('```' + args.join(" ") + '```')
        .setTimestamp()
        .setColor("BLACK")
        .setTimestamp()
        .setFooter("Copyright ©️  2022, Mythic Realms, or its associates. All Rights Reserved.")

    message.channel.send({embed: sayEmbed}).then(embedMessage => {
    embedMessage.react('✅');
    })
    
        const filter = (reaction, user) => reaction.emoji.name === '✅' && user.id === message.author.id;
        const collector = message.createReactionCollector(filter, { max: 1, time: 5 * 60 * 1000 });
        
    collector.on('collect', () => {
      message.clearReactions();

      console.log('SUCCESS');
    });
  },
};

Please help with this bot :< thank you.

How to load an external html and it´s css files with XMLHttpRequest?

I want to load an html and it`s css files into other html with XMLHttpRequest()
The problem is that the html file is loaded but not it´s css file.

it is possible to load the file so that it looks the same as the original?

I have achieved this by loading it into a full screen iframe but would like to achieve this without the use of an iframe.

var xmlhttp = new XMLHttpRequest();

xmlhttp.onreadystatechange = function() {
    if (xmlhttp.readyState == XMLHttpRequest.DONE) {   // XMLHttpRequest.DONE == 4
        document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
    }
};

xmlhttp.open("GET", "myHtmlWithCss.html", true);
xmlhttp.send();

Regex to convert camel case to snake case inside a sentence

I’m trying to change my apps database and I need to change all columns to snake case in my js code.

Columns are hard coded as string like this

name: ‘ColumnName’

I want to change this occurrences to

name: ‘column_name’.

I have this regex

    ([a-z])?([A-Z])

Which allows me to replace all camel cases everywhere but I can’t use it since it would replace other parts of the code.

Is this doable using only regex?

jQuery Validation on dynamic form

I’m working on a legacy app that uses jquery validation on a dynamic form. Now I’m trying to pass the name of each textarea input to the validation but doesn’t work or maybe I’m doing it wrong. I want to the fieldName variable inside validate(see below).

<form class="comment_form" id="update_comment">
  @foreach($user as $key => user)
   <textarea class="form-control" name="comment[$key]"></textarea>
  @endforeach
</form>

<script>
 var $fieldName;
    $.validator.addMethod("allowedChars", function (value) {
        var reg = /^[ A-Za-z0-9 _@./*!'"#&+-]*$/;
        return reg.test(value);
    });

    //foreach loop here
    var comment = document.getElementsByTagName("textarea");
    for($i=0; $i < comment.length; $i++) {
        fieldName = comment.name; // I want to the field name insode validate below
        console.log(fieldName);
        $("#update)comment").validate({
            rules: {
                fieldName: {
                    allowedChars: true
                }
            },
            messages: {
                fieldName: "Allowed special characters: _@./*!'"#&+-"
            }
    });

};

Looping through array with forEach

I am trying to make a basic program that loops through an array and logs the ‘place’ & ‘distance’ to the console. My program isn’t working as intended and won’t log the values to the console. What am I doing wrong and how can I fix it?

let destinations = [
  {place: ['Dubai'],
  distance: 7276},
  {place: ['Sydney'],
  distance: 8759},
  {place: ['London'],
  distance: 4166},
  {place: ['tokyo'],
  distance: 5754},
  {place: ['Seoul'],
  distance: 6037},
];

destinations.forEach(spot => {
    if (spot.length < 6) {
      console.log(`${spot} is an interesting vacation spot.
      Let's see how far it is before we pull the trigger`);
      destinations.forEach(howFar => {
        if (howFar < 6000) {
          console.log(`${spot} is close enough. Let's go there!`);
        } if (howFar > 6000) {
          console.log(`Nevermind. ${spot} is too far.`);
        }});
    }
});

Vite bundeled npm-packaged dynamic component not rendering

I am struggling with getting a packaged component to display its dynamically loaded components. When I run the bundle standalone everything works nice. When used as external library the props arrive at the lib, but the dynamic components are not rendered.

package.json - package
{
  "name": "pfg-formwizard",
  "version": "0.0.0",
  "main": "./dist/pfg-formWizard.umd.js",
  "module": "./dist/pfg-formWizard.es.js",
  "exports": {
    ".": {
      "import": "./dist/pfg-formWizard.es.js",
      "require": "./dist/pfg-formWizard.umd.js"
    },
    "./dist/style.css": "./dist/style.css"
  },
  "files": [
    "dist"
  ],
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "uuid": "^8.3.2",
    "vue": "^3.2.25"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.0.0",
    "autoprefixer": "^10.4.2",
    "postcss": "^8.4.6",
    "tailwindcss": "^3.0.18",
    "vite": "^2.7.2"
  }
}
vite.config.js - package
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
const path = require('path');

export default defineConfig({
  build: {
    lib: {
      entry: path.resolve(__dirname, "src/components/index.js"),
      name: "pfg-formWizard",
      fileName: (format) => `pfg-formWizard.${format}.js`
    },
    rollupOptions: {
      external: ["vue"],
      output: {
        globals: {
          vue: "Vue",
        }
      }
    }
  },
  plugins: [vue()]
})
published component - package
<template>
  <div class="bg-amber-200 pfg-formWizard h-full">
    <h1 class="max-w-5xl mx-auto text-xl">{{form.name}}</h1>

    <form @submit.prevent="onSubmit" class="w-full">
      <div class="max-w-5xl container mx-auto">
        <p>{{form.schema}}</p>
        <p
            v-for="element in form.schema"
        >{{element}}</p>
        <component
          v-for="element in form.schema"
          :is="components[element.component]"
          :section="element"
        ></component>
      </div>
      <FormControls class="max-w-5xl container mx-auto" />
    </form>
  </div>

</template>

<script>
export default {
  name: 'FormWizard',
}
</script>
<script setup>
import FormSection from "./wizard/FormSection.vue";
import FormControls from "./wizard/FormControls.vue";


const components = {
  FormSection,
}

const props = defineProps({
  form: {
    type: Object,
    required: true
  },
})
[...]
</script>

Note that when using this package this FormWizard component renders correctly, the {{form.name}} displays and renders too.

The dynamic <component :is=”[…]” does somehow not work, although the props are there.
The

{{form.schema}}

displays the json object array string correctly.
The does not display at all.

/src/components/index.js - package
import FormWizard from "./FormWizard.vue"

export {
    FormWizard,
}

All my research led to dead ends. What am I missing?
Any hint greatly appreciated!

Accessing a variable outside of https.get() function [duplicate]

I have this function for downloading a file from a url. It works fine saving the file with its respective extension (e.g. file.png, file.mp4).

async function download(url) {
  const req = https.get(url, async function (res) {
    const fileName =
      "file." + (await res.headers["content-type"].split("/")[1]);
    const fileStream = await fs.createWriteStream(fileName);
    res.pipe(fileStream);

    fileStream.on("error", function (error) {
      console.log("Error writing to the stream.", error);
    });

    fileStream.on("finish", function () {
      fileStream.close();
      console.log(`Successfully downloaded ${fileName}`);
    });
  });

  req.on("error", function (error) {
    console.log("Error downloading the file.", error);
  });
}

The thing is that I want to access the variable ‘fileName’ after the function has been called, I tried to return it but is not working. I want something like this working, any ideas? Thank you

const value = download(url)
console.log(value) // prints file.png

Why is my array coming up as undefined when I try to access the individual elements?

I’m trying to load two user-defined csv files and programmatically compare them (essentially trying to find errors in the files and report those errors to the user). I’m uploading the first and am running into a problem. When I display the entire array console.log(results); it shows me the entire array in the console. However if I try to get the first row console.log(results[0]); I simply see ‘undefined’ in the console. I also have the same issue when I call console.log(deviceData); in a later snippet of code (works for the entire array but the second I try to access an element I get an undefined). What am I doing wrong?

<script>
    var deviceData = new Array();
    const uploadConfirm = document.getElementById('uploadConfirm').addEventListener('click', () => {
        Papa.parse(document.getElementById('deviceFile').files[0],
        {
            download: true,
            header: false,
            skipEmptyLines: true,
            complete: function(results){
                console.log(results[0]);
                deviceData = results;
            }
        });
    });

How to render conditional content in react

I am trying to figure out how to tweak this boilerplate repo, so that on the index page, I can either render one page for the logged in user, or another for anyone else. The boilerplate index renders the same page, always, but adds an extra bit to it if there is an authenticated user.

Currently, when I try:

return (
    <Box>
      <Head>
        <title>title</title>
      </Head>
      <div>
      <Limiter pt={20} minH="calc(100vh - 65px)">
        <Center flexDir="column">
        {!me  &&
            <Box textStyle='h1' mb={8} mt={8} textAlign="center" >
              <HomeLandingPage />
            </Box> 
        } 
        {me && router.replace("/dashboard")}
        
        </Center>
      </Limiter>
      </div>
    </Box>
  )

I get no errors in the terminal, but I get this error in the browser:

Error: Objects are not valid as a React child (found: [object
Promise]). If you meant to render a collection of children, use an
array instead.

If I remove the second condition (ie me is true), I can render the HomeLandingPage without an error, but I just get an empty page if !me is false. The same is not true if I delete the !me condition and just try to render the logged in user page. I get the same error as when I try to use both alternatives.

I don’t know where to put an array to deal with this. Some posts about this error resolved their problems by putting everything inside a div tag. I’m using ChakraUI, which calls a div a Box, which I am using, but I tried adding extra divs at each level of the home page to try and find a version that works – none did.

I was trying to rely on the login redirect on successful authentication handler, which has:

  const onSubmit = (data: LoginInput) => {
    return form.handler(() => login({ variables: { data } }), {
      onSuccess: async (data) => {
        await fetch("/api/login", {
          method: "post",
          body: JSON.stringify({ [LOGIN_TOKEN_KEY]: data.login.token }),
        })
        client.writeQuery<MeQuery>({ query: MeDocument, data: { me: data.login.user } })
        router.replace(redirect || "/dashboard")
        // router.replace('/dashboard')
        // router.replace('/profile/index')
        // console.log(redirect, REDIRECT_PATH)
        
      },
    })
  }

I expected this handler to redirect to the /dashboard on successful login – but it does not.

If I remove the me handler from the index.tsx page, I just get an empty page page when I authenticate, and I can then add /dashboard to the browser url to navigate to the page that I am trying to redirect to on successful authentication.

My first line of enquiry to solve this is why I can’t have a redirect in the home page if me is true.

Are there any clues that could inspire the direction of my research into next steps?

Export two pages of a spreedsheet

I want export two pages of a same spreedsheet to one single file, how can i do it?

var ssID = “ssID”

var url = “https://docs.google.com/spreadsheets/d/”+ssID+”/export?format=xlsx&gid=AAAA”;

var url2 = “https://docs.google.com/spreadsheets/d/”+ssID+”/export?format=xlsx&gid=BBBB”;

var params = {method:”GET”, headers:{“authorization”:”Bearer “+ ScriptApp.getOAuthToken()}};

var response = UrlFetchApp.fetch(url, params);

DriveApp.createFile(response).setName(name);

Undefined variable when trying to pass by ajax to PHP

I am trying to pass variables while user press button from JS to PHP using ajax. I am trying to find solution why it is not working but I have no idea.. This is a ajax code in my js file. I am also not sure if I set if(isset($_POST[“add-review”])) correct, I put add-review to get this when user press button name = “add-review”

html

<button type="button" id="add-review" name="add-review" class="btn btn-primary"><a style="text-decoration: none; color: white;" href="rating-data.php">Add review</a></button>

js file

$('#add-review').click(function(){

                        var user_name = $('#reviewer-name').val();

                        var user_review = $('#review').val();

                        console.log(user_name);
                        console.log(rating_index);
                        console.log(user_review);
                        var rating_index = 0;

                        if(user_name == '' || user_review == '')
                        {
                            alert("Please Fill Both Field");
                            return false;
                        }
                        else
                        {
                            $.ajax({
                                url:"rating-data.php",
                                method:"POST",
                                data:{
                                    index: rating_index,
                                    user_name: user_name,
                                    user_review: user_review,
                                },
                                success:function(data)
                                {
                                    $('#review_modal').modal('hide');

                                    load_rating_data();
                                    console.log(data);

                                }
                            })
                        }

                    });

and php rating-data.php

<?php 
include 'connection.php';
echo "hello";
echo $_POST['index'];

if(isset($_POST["add-review"]))
{
    $rating_index= $_POST['rating_index'];
    $name= $_POST['user_name'];
    $review = $_POST['user_review'];
    $datatime = time();

    $query = "
    INSERT INTO review_table 
    (user_name, user_rating, user_review, datetime) 
    VALUES (
        name, rating_index, review, datatime
    )";

    $query_run = mysqli_query($conn, $query);

    if($query_run){
        echo "Your Review & Rating Successfully Submitted";
    } else{
        echo '<script type="text/javascript"> alert("Something went wrong") </script>';
        echo mysqli_error($conn);
    }


}


?>

and when I echo I got Undefined on line 4