How to get My PUBLIC IP address Using Node js

I want to get my Public IP address using Node js only

For example when i search on Google
“What is my Ip address “

Gives me output like
10X.XX.XX.XXX

How to get this Ip address Using node js without importing any Libraries like ip , Public-ip etc …

I want to write my Custom Code to get public ip
Without sending requests to other websites like whatismyipaddress.com , ipconfig.com etc …

How do I map state into a component as a prop?

Hey for some reason my questions aren’t being rendered. I feel my issue may be with my QuizData.map but I can’t tell what the issue is because I can console.log console.log(quizData.map(item => item.question)) and get the results.

Any clue as to what may be causing this issue? Thank you!

Parent Component

export default function QuizData() {

const [quizData, setQuizData] = React.useState([{
    question: "",
    answers: "",
    correctAnswer: "",
    selectedAnswer: ""
}]);
React.useEffect(() => {
    fetch("https://opentdb.com/api.php?amount=5&category=12&difficulty=medium&type=multiple")
        .then(res => res.json())
        .then(data => setQuizData(data.results.map(item => ({
            question: item.question,
            answers: item.incorrect_answers.concat(item.correct_answer),
            correctAnswer: item.correct_answer
        }))))
},[]) 
return (
    <div>
        
        {quizData.map((item) => {
            <div>
                <Question 
                    question={item.question}
                    answers={item.answer}
                    chosenAnswer={quizData.selectedAnswer}
                    updateAnswers={handleSelectedAnswer}
                />
            </div>
        })}
          <button
            onClick={() => {
                    checkSelectedAnswer();
                    scoreQuiz();
                    finishQuiz()
                    }
                }>
            Check answers
        </button>
  </div>
)}

Child component

export default function Question(props) {

return (
    <div>
                
                    {props.question.map(item => <h3>item</h3>)}
                    
                    {props.answers.map((item, index) => {
                        <div key={index}>
                            <input
                                type="radio"
                                name={`answer option-${item}`}
                                id={`answer-options-${index}`}
                                value={props.chosenAnswer}
                                onChange={props.updateAnswers}
                            />
                            <label htmlFor={`answer-options-${index}`}>{answerOption}</label>
                        </div>
                    })}
                   
    </div>
)}

Jquery data tables need to show only selected rows from an integer array of IDs

I have a drop down with checkboxes in it. When I select multiple items, I have a method which gets those IDs in an integer array. In my data table one of the column, lets say ‘User_ID:name’ has those IDs. I want to loop through the data table and show only rows of selected IDs in the integer array. If array is empty, no rows should be visible.

I wrote a method, but it’s only showing me only 1 row and it keeps overwriting that row when looping through.

var Gridupdate = function () {
                int[] checked = Checkbox.getCheckedIds(); /// integer array of selectedIDs from a checkbox
                if (dtable) {
                    for (i = 0; i < checked.length; i++) {
                        dtable.column("User_ID:name").search(checked[i].toString()).draw();
                    }
                }
            }

Using Firebase v9, how can I add the user to the user collection upon logging in with gmail?

How can I add a user to the users collection logging in with Gmail?
I tried the addUser but it does not work. I’m quite new to Firebase v9

//firebase
    import { signInWithPopup, GoogleAuthProvider } from "firebase/auth";
    import { auth, signInWithGoogle, db } from "../../Firebase/utils";
    import { doc, setDoc, collection } from "firebase/firestore";

const Login = (props) => {
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");

  const addUser = async () => {
    const userRef = doc(db, "users", auth.currentUser);
    setDoc(userRef);
  };

  useEffect(() => {
    addUser();
  }, []);

  const googleHandler = async () => {
    signInWithGoogle.setCustomParameters({ prompt: "select_account" });
    signInWithPopup(auth, signInWithGoogle)
      .then((result) => {
        // This gives you a Google Access Token. You can use it to access the Google API.
        const credential = GoogleAuthProvider.credentialFromResult(result);
        const token = credential.accessToken;
        // The signed-in user info.
        const user = result.user;
        // redux action? --> dispatch({ type: SET_USER, user });
        addUser();
        console.log(auth.currentUser, "login page");
      })
      .catch((error) => {
        // Handle Errors here.
        const errorCode = error.code;
        const errorMessage = error.message;
        // The email of the user's account used.
        const email = error.email;
        // The AuthCredential type that was used.
        const credential = GoogleAuthProvider.credentialFromError(error);
        // ...
      });
  };

  return (
    <>
        <form>
           <Button onClick={googleHandler}>Login with Gmail</Button>
        </form>
    </>
  );
};

export default Login;

These are my package.json just to be sure:

enter image description here

Multer give undefined for req.file

I’m make api to upload files using node js.

i using multer for handle multipart/form-data
but when i console.log(req.file) it appears undefined

Route

const uploadController = require('../controller/upload.server.controller');
const multer = require('multer');

const upload = multer({ dest: 'uploads/' });

/**
 * Routes
 */
module.exports = function (app) {
  app
    .route('/api/upload')
    .post(upload.single('image'), uploadController.upload);
};

Controller

exports.upload = async function (req, res) {
    console.log(req.file);
};

my request with postman

request with postman

Perform Simple Division In HTML

I have a product website that lists the product price based on a box of 20 units ($20/box for this example). I’d like to show the per-unit cost next to the box cost, or $1.00.

The HTML already defines [PRICE] as the tag for the price of the box. I thought it would be simple enough to divide this by 20 using a <script>, but I’m wrong!

I came up with this:

<!--START: quantity_items-->
 <tr>
  <td>[lowbound][highbound]</td> //this the volume band; example - buy 3 to 5 boxes and pay a certain price, called [PRICE].
  <td>[PRICE]
   <script>
    var numOne=[PRICE], numTwo=20, res;
    res = numOne/numTwo;
    document.write(" ($" + res + "/unit)");
   </script>
  </td>
 </tr>
<!--END: quantity_items-->

…with the expected outcome being:

3 – 5 || $20.00 ($1/unit)

This is a table, obviously (td and tr tags), so the calculation would repeat for each row.

Now, calculations work using this tutorial (I can see them on my site):

<script>
  var numOne=12, numTwo=20, res;
  res = numOne + numTwo;
  document.write(" ($" + res + "/unit)");
</script>

But when I replace the 12 with [PRICE], it fails. What is happening here? I assume that [PRICE] needs to be introduced into the <script> somehow, but how it that done?

Close modal using javascript setTimeout

Once my ajax call has finished I want to display a message for 3 seconds. I am using a modal. However, the timeout is not being triggered and there is no console log error. I have been through the myriad of online examples and none resolve the issue. My code is:

.done(function(responseJson1) {
    modal.style.display = "block";
            
    setTimeout(function(){
        alert("Timed out");//temporary to see if the time out is triggered
        modal.style.display = "none";
    }, 3000);
})

Out side of the ajax call I have:

//Get the modal
var modal = document.getElementById("myModal");

//Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];

//When the user clicks on <span> (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}

//When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
    if (event.target == modal) {
        modal.style.display = "none";
    }
}

The css:

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.modal-content {
    background-color: #fefefe;
    margin: 15% auto; /* 15% from the top and centered */
    padding: 20px;
    border: 1px solid #888;
    width: 80%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.close {
    color: #aaa;
    float: right;
    font-size: 28px;
    font-weight: bold;
}

.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}

useState & splice Function not updating array correctly [duplicate]

I am creating an array called indicator_box (which is the length of numberofQuestions).
I am using useState to try to update the array with ‘correct/wrong’ everytime changeHandler is clicked.

When trying to debug I know indicator_box is updated when changeHandler is clicked, however this only seems to be temporary. As the array resets to empty when moving through the quiz app.

Any help would be great!

import React, { useState, useEffect, useRef } from 'react';

const Time_Question = ({ data, onAnswerUpdate, numberOfQuestions, activeQuestion, onSetActiveQuestion, onSetStep }) => {
  const [selected, setSelected] = useState('');
  const [error, setError] = useState('');
  const radiosWrapper = useRef();
  const [results, setResults] = useState([]);
  const [clickedItem, setClickedItem] = useState(null);
  const [indicator_box, setIndicator_box] = useState([]);


  var lengthArray = numberOfQuestions
  let indicator_box=[];
  for(; lengthArray--;)
    indicator_box.push([]);

  const changeHandler = (element) => {
    setSelected(element.target.value);
    const id = element.target.id;
    const class_d = element.target.className;
    let selectedTag = element ? parseInt(element.target.id, 10) : null;
    setResults([...results, { selectedTag}]);
    const selected = data.options[id]
    onAnswerUpdate(prevState => [...prevState, { q: data.question, a: selected }]);
    if ((data.options[id] === data.answer)){
      updateIndicator("correct");
    } else {
      updateIndicator("wrong");
    }
    if(error) {
      setError('');
    }
  }

  const updateIndicator = (markType) =>{
      setIndicator_box(indicator_box.splice(activeQuestion,1, markType));
  }

  const nextClickHandler = (element) => {
    if(selected === '') {
      return setError('Please select one option!');
    }
    setSelected('');
    if(activeQuestion < numberOfQuestions - 1) {
      onSetActiveQuestion(activeQuestion + 1);
      setClickedItem("");
    }else {
      onSetStep(3);
    }
  }



  return(
          <div className = "quiz-box custom-box" >
          <div className = "question-number" >
          <span > Question {activeQuestion+ 1} of < /span> {numberOfQuestions} </div>
                <div className="question-text">
                {data.question}
                </div>

          <div className="option-container ">
              {data.options.map((option, index) => (
          <div id={index} value={option}
           className={(index === clickedItem) & (data.options[index] === data.answer) ? "option correct already-answered" :
           (index === clickedItem) & (data.options[index] != data.answer) ? "option wrong already-answered":
           "option"}
          onClick={changeHandler} key={index}
            > {option}
          </div>
        ))}
          </div>

          <div className="next-question-btn">
          {error && <div className="has-text-danger">{error}</div>}
             <button type="button" className="btn" onClick={nextClickHandler}>Next</button>
          </div>
           <div className="answers-indicator">
            {indicator_box.map((indicator, index) => (
             <div id={index} key={index}
             className={ (indicator === "correct") ? "correct" :
              (indicator != "wrong") ? "wrong":
             ""}>{indicator}
           </div>
          ) )}
           </div>


          </div>
  );
}

export default Time_Question;

Querystring is striked through

Can somebody help me out. Why is the querystring striked through?
My code:
[![querystring problem][1]][1]


const handler = async (event, context) => {
  // Only allow POST
  if (event.httpMethod !== "POST") {
    return { statusCode: 405, body: "Method Not Allowed" };
  }

  // When the method is POST, the name will no longer be in the event’s
  // queryStringParameters – it’ll be in the event body encoded as a query string
  const params = querystring.parse(event.body);
  console.log(params);

  const { firstname, lastname, country } = params;


  // maak er een object van dat de data terugstuurt naar de user
  const userData = {
    firstname,
    lastname,
    country

  }

  return {
    statusCode: 200,
    body: JSON.stringify(userData),
  };
};
module.exports = {handler};

In Vscode it shows up as this:
[1]: https://i.stack.imgur.com/lhX7G.png

I copied the code straight from Netlify.
2 [https://functions.netlify.com/playground/#hello%2C-%7Bname%7D-(post-version)]

How can I solve this?

Import of Svelte library not working in online editors but locally

I’m kinda confused how to properly export my own JS library (for Svelte).
When I import the library on a local project (example local project) then everything works just fine, but when I import it in a online editor like Svelte REPL or CodeSandbox it just won’t work, because the module can’t be found.

The file that exports: https://github.com/DanielSharkov/svelte-router/blob/master/src/index.js

Replication on CodeSandbox: https://codesandbox.io/s/jovial-morning-5o7xr?file=/router.js

To replicate it on Svelte REPL (I can’t safe to share it, because of the error):

<script>
    import {SvelteRouter} from '@danielsharkov/svelte-router'
    console.log(SvelteRouter)
</script>

For more details of the library you may inspect the repository: https://github.com/DanielSharkov/svelte-router

The files src/router.js and src/router.mjs aren’t in the repository, as these are builds of index.ts.

Discord.js client mention and text behind command

I want it to ping the client who sent the message and to write the text after the command. Please help, thank you.

client.on("messageCreate", function(message) {
    if (!message.content.startsWith(prefix)) return;

    const commandBody = message.content.slice(prefix.length);
    const args = commandBody.split(' ');
    const command = args.shift().toLowerCase();
    const channel = client.channels.cache.get('939145964961292298');
    message.delete()

    if ("napad") {
        const { MessageEmbed } = require('discord.js');
        const exampleEmbed = new MessageEmbed()
            .setColor('#6d4193')
            .setTitle('mention sender')
            .setDescription('message after command')
            .setTimestamp()
            .setFooter({ text: 'PixelRP | BOT by ejdamec', iconURL: 'https://cdn.discordapp.com/attachments/939271126784303104/939453115810320414/logo_pure.png' });

        channel.send({ embeds: [exampleEmbed] });
    }
});

why nested foreach within javascript loop not working?

I am trying to check if the answers from a user are correct. The answers of the user are stored in variable “stad”. The correct options are stored in variable “collectie”. However, this variable is an array with a nested array. So i first loop through the “collectie”, check if the collectie element is not an array and if not, check that the submitted value is within this collectie element.

If the collectie element is an array, i have to alter a little bit the function so the variable checks whether the answer is within the nested array.

I have the following:

function nakijken() {
var collectie = ["parijs", "8", "ijsselmeer", ["Volkswagen", "Audi", "Opel", "Porsche", "BMW", "Mercedes", "Mercedes-Benz"],
["Texel", "Vlieland", "Terschelling", "Ameland", "Schiermonnikoog"]];
var stad = [];
var a = 0;
stad.push(document.getElementsByTagName("input"));
collectie.forEach(uitpakken);
function uitpakken(antwoord) {
    if (!Array.isArray(antwoord)) {
        stad.forEach(myfunction);
        function myfunction(item) {
            if (antwoord.includes(item.value.toLowerCase())) {
                item.style.background = "green";
                a++;
            } else {
                antwoord.style.background = "red";
            }
        }
    }
    else{
        antwoord.Foreach(uitpakken);
        function uitpakken(antwoord) {
        stad.forEach(mysecondfunction);
            function mysecondfunction(item) {
                if (antwoord.includes(item.value.toLowerCase())) {
                    item.style.background = "green";
                    a++;
                } else {
                    antwoord.style.background = "red";
                }
            }
        }
    }
}

However, i get the error: item.value is not defined.
Within the console, i see that item is a collection of inputs, and not a single input.

Why is this not working?

How to load javascript modules into an array?

I have a directory tree that contains javascript files which each export a class. I need to load all these modules into an array that maps to how these files are organised on the file system:

For example:

// rootDir/fileA.js

module.exports = class A { … }

// rootDir/subDir/fileB.js

module.exports = class B { … }

—->

[
  { 
    path: ‘rootDir/fileA.js’,
    value: class A { … }
  },
 { 
    path: ‘rootDir/subDir/fileB.js’,
    value: class B { … }
  }
]

Ideally they would be loaded into an array with the above structure. The directory tree could have many files organised in any way possible.

I’ve tried doing this using require, but since it’s synchronous, that only works if I run it at the very top of my code. When I run it at a lower level, the subsequent code executes before all the modules are loaded, and so errors because the classes aren’t there when I try to use them.

Previous question that documents what I tried for a similar but different use case:

How to require directories using async / await

How can I create the array of class objects in a way that my code can use the loaded modules?