I cannot post api’s data locally

Im trying to make a simple APi web app and i cannot post the data into localhost!

I tried to find answers accros the web but i couldnt make it

const express = require("express");
const app = express();
const https = require("node:https");
const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: false }));


app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

app.post("/", (req, res) => {
  const url = "https://favqs.com/api/qotd?856edacaf39b0dc9be175cb84bd3f072";
  
  https.get(url, (response) => {
    console.log("statusCode:", response.statusCode);

    response.on("data", (data) => {
      const quotesData = JSON.parse(data);
      //const author = quotesData.quote.author;
      const quotes = quotesData.quote.body;

      res.write(quotes);
      res.send();
    });
  });
});

app.listen(3000, () => {
  console.log("app listening on port 3000");
});

Firestore query Cursors Generating Dynamic Queries

In Firestore when i am writing the query and executing like this , it is working fine

_query =   query(collectionTestingRef  , 
where('name','==', 'him') , 
 limit(4));

But when i am taking the query in some variable and then using (required because i need to run a loop and add unknown where condition) , it is not working .

var _localWherequery = “where(‘name’,’==’, ‘him’)” ;
_query = query(collectionTestingRef ,
_localWherequery,
limit(4));

How can i achieve this dynamism , knowing that i dont know number of where clauses and i want to use query cursors only in firestore .

React native ios build failed showing multiple instances of the same simulator and same UDID, “com.apple.compilers.llvm.clang.1_0.compiler” flagged

`2023-04-10 12:54:39.743 xcodebuild[37229:209830] DVTCoreDeviceEnabledState: DVTCoreDeviceEnabledState_Disabled set via user default (DVTEnableCoreDevice=disabled)
— xcodebuild: WARNING: Using the first of multiple matching destinations:
{ platform:iOS Simulator, id:F74E3465-A58E-4B17-BF2B-1CB79F225F2F, OS:16.4, name:iPhone 14 }
{ platform:iOS Simulator, id:F74E3465-A58E-4B17-BF2B-1CB79F225F2F, OS:16.4, name:iPhone 14 }
** BUILD FAILED **

The following build commands failed:
CompileC /Users/devansh/Library/Developer/Xcode/DerivedData/RN_App-eibylxcwymbqneczxtsodzlvaqxg/Build/Intermediates.noindex/Pods.build/Debug-iphonesimulator/React-Codegen.build/Objects-normal/arm64/FBReactNativeSpec-generated.o /Users/devansh/Desktop/rn-temp-engin2.0/ios/build/generated/ios/FBReactNativeSpec/FBReactNativeSpec-generated.mm normal arm64 objective-c++ com.apple.compilers.llvm.clang.1_0.compiler (in target ‘React-Codegen’ from project ‘Pods’)
(1 failure)`

When trying to build the ios project in a react native project, I am encountered with this error. I have uninstalled and reinstalled the XCode_14.3, followed the commands to clear the npm cache, deleted Pods, cleared Derived_Data of XCode and even deleted the devices which were highlighted, but this error is shown with every next device in the list shown by xcrun simctl list devices.

when I compare array and copy of array its showing Flase Why?

why copy of array and array showing flase when compare the even their type is same and values too

    const array1 = [1, 30, 4, 21, 100000, 99];
    console.log(typeof[...array1]);
    console.log(typeof(array1));
    console.log(array1);
     console.log([...array1]);
    console.log([...array1] === array1);
    console.log(array1 === array1);

OUTPUT

object

object

1, 30, 4, 21, 100000, 99

1, 30, 4, 21, 100000, 99

false

true

console.log([...array1] === array1);
This result Must Be True

How can i display meta data in the stripe

I used this metadata as array of object [{},{},{}]

const sessionData = {
      payment_method_types: ["card"],
      shipping_address_collection: {
        allowed_countries: ["US", "CA", "KE"],
      },
      line_items: [
        {
          price_data: {
            currency: "USD",
            product_data: {
              name: title,
              description: description,
              metadata: {
                endpoints: JSON.stringify(data),
              },
            },
            unit_amount: totalPrice.toFixed(0) * 100,
          },
          quantity: 1,
        },
      ],
      mode: "payment",
      customer: customer.id,
      success_url: `${getBaseClientUrl}/stripe/success`,
      cancel_url: `${getBaseClientUrl}/stripe/cancel`,
    };

    const session = await createCheckoutSession(sessionData);

but it render only title price and description on the checkout session on stripe ui , any one can help me over there ,
thank you in advance.

i want to return the metadata on the stripe checkout session ui

Use copyfiles with file path as attribute

I want to copy this color.ini file to this location %appdata%/spicetify/Themes/Nord-Spotify, so i put this in package.json and it works

"build-colors": "copyfiles --flat theme/color.ini %appdata%/spicetify/Themes/Nord-Spotify",

But i dont want to specify the folder instead want to specify the file path %appdata%/spicetify/Themes/Nord-Spotify/color.ini

facing issue to get xpath of the element present in Shadow DOM

enter image description here

I am using robot framework for automation and want to click on element print button(Please refer attach image for Html Code) on Shadow Dom. I have created variable using js path but it is not working. Can any one help to find exact xpath of the element

*** Variables ***

${chrome} chrome

${print} ${printIRCF1}

${JSPath}=  document.querySelector('print-preview-app').shadowRoot           
       ...  .querySelector('print-preview-sidebar')  
       ...  .querySelector('print-preview-button-strip').shadowRoot  
       ...  .querySelector('controls')  
       ...  .querySelector('action-button').shadowRoot

Can any one help me with the correct JsPath or with xpath so that I can use it in my code

Extra line break occuring with syntax highlighting (prism js)

I am making a syntax highling code editor in HTML, JS, and CSS.

How it Works:
There are two divs that overlap. The one on top is the one that you edit. The one below mimicks what you type, but is formatted (using prism js).

Problem:

Whenever there are consecutive line breaks (more than one line break at a time), the formatted code appears that many times below the typed text.

Example:

Typed Text:

<span></span>



<h1></h1>

Formatted:

<span></span>






<h1></h1>

Code

`#codeContainer {
            position: fixed;
            top: 10%;
            left: 0%;
            z-index: 1;
            width: 100%;
            height: 90%;
            outline: 0;
        }

        #code {
            position: absolute;
            left: 0%;
            top: 0%;
            width: 100%;
            height: 100%;
            background-color: transparent;
            font-size: 14px;
            line-height: 1.5;
            white-space: pre-wrap;
            overflow: auto;
        }

        #highlight {
            position: absolute;
            left: 0%;
            top: 0%;
            z-index: 0;
            width: 100%;
            height: 100%;
            background-color: white;
            font-size: 14px;
            color: white;
            line-height: 1.5;
            white-space: pre-wrap;
            overflow: auto;
            margin-top: -6px;
            padding-left: 5px;
        }

        pre code {
            position: absolute;
            left: 0%;
            top: 0%;
            width: 100%;
            height: 100%;
            padding-left: 5px;
        }

        #code,
        #highlight {
            font-size: 14px;
            line-height: 1.5;
            font-family: 'Courier New', Courier, monospace;
        }
<div id="codeContainer">
        <div id="highlight"></div>
        <pre id="code">
            <code contenteditable="true"></code>
        </pre>
    </div>
const codeElement = document.getElementById('code');
        const highlightElement = document.getElementById('highlight');

        function updateHighlight() {
            const code = codeElement.innerText;
            var highlightedCode = Prism.highlight(code, Prism.languages.html, 'html');

            highlightElement.innerHTML = highlightedCode.toString();
        }

        codeElement.addEventListener('input', updateHighlight);

I am not really sure how I could fix this, and I don’t really know what is causing the issue.
Any help is appreciated. Thanks!

What’s the correct way to render a component on data change in the database? React

I working on a MERN project for learning purposes (not YT follow-up). I have a user model with a rank of 0 as default and with different score fields. I have created an endpoint that when the score fields meet certain conditions, the user rank gets updated 1. So far so good here and it works. My next step is to show a ‘you ranked up’ pop-up when the user rank changes and I am not sure what the best practice is for that. It’s a math-practice challenge and I want the pop-up to show between the end of the game and final score component. Any help is appreciated.

Endpoint:

import User from "../models/userModel.js";
import jwt from "jsonwebtoken";
import asyncHandler from "express-async-handler";

export const rankUp = asyncHandler(async (req, res) => {
  // Extract token from headers
  const token = req.headers.authorization.split(" ")[1];

  // Find the user by token
  const decoded = jwt.verify(token, process.env.JWT_SECRET);
  // Find user by id
  const user = await User.findOne({ _id: decoded.id });

  if (!user) {
    return res.status(404).send("User not found");
  }

  let newRank;

  if (
    user.userStats.totalScore === 5000 &&
    user.userStats.totalAdditionScore >= 1000 &&
    user.userStats.totalAdditionScore >= 1000 &&
    user.userStats.totalSubtractionScore >= 1000 &&
    user.userStats.totalMultiplicationScore >= 1000 &&
    user.userStats.totalOrderedScore >= 1000
  ) {
    newRank = 1;
  } else {
    throw new Error('Conditions not met')
  }

  // Save the updated user
  const updatedUserRank = await User.findByIdAndUpdate(
    { _id: decoded.id },
    { $set: { userRank: newRank } },
    { new: true }
  );

  if (updatedUserRank) {
    res.json({updatedUserRank});
  } else {
    res.status(400);
    throw new Error("Something went wrong");
  }
});

The component that I want to show the pop-up:

import { Divider, List, TextField, Typography } from "@mui/material";
import React, { useEffect } from "react";
import Navbar from "../components/Navbar";
import Container from "@mui/material/Container";
import Box from "@mui/material/Box";
import Button from "@mui/material/Button";
import { useState } from "react";
import { useNavigate } from "react-router";
import GameInfo from "./GameInfo";
import { useSelector, useDispatch } from "react-redux";

import {
  earnLife,
  gainPoints,
  gainTime,
  isFinished,
  loseLife,
  loseTime,
  restart,
} from "../features/gameSlice";
import { updateScore } from "../statsHandler";

const correctAnswer = <Typography>Correct!</Typography>;
const wrongAnswer = <Typography>Wrong!</Typography>;
const enterAnswer = <Typography>Enter your answer!</Typography>;

const MainInput = ({ operation, calculation }) => {
  const [enteredValue, setEnteredValue] = useState("");
  const [correctValue, setCorrectValue] = useState(false);
  const [calculatedNums, setCalculatedNums] = useState({});
  const [isIncorrect, setIsIncorrect] = useState(false);
  const [generateNewNumbers, setGenerateNewNumbers] = useState(false);
  const [haveToEnterAnswer, setHaveToEnterAnswer] = useState(false);
  const [streak, setStreak] = useState(0);

  const seconds = useSelector((state) => state.game.seconds);
  const points = useSelector((state) => state.game.points);
  const lives = useSelector((state) => state.game.lives);
  const gameOver = useSelector((state) => state.game.isFinished);
  const gameStart = useSelector((state) => state.game.startGame);

  const user = JSON.parse(localStorage.getItem("user"));

  const token = user.token;

  let finalScore = points;

  const navigate = useNavigate();

  // FIX THE UNDEFINED ISSUE

  // FIX THE UNDEFINED ISSUE

  // FIX THE UNDEFINED ISSUE

  useEffect(() => {
    if (gameOver) {
      updateScore(finalScore, operation, token);
    }
  }, [gameOver]);

  useEffect(() => {
    if (correctValue && streak === 4 && lives < 4) {
      dispatch(earnLife());
      setStreak(0);
    }
  }, [streak]);

  useEffect(() => {
    setCalculatedNums(calculation());
    setGenerateNewNumbers(false);
    setCorrectValue(false);
    setEnteredValue("");
  }, [generateNewNumbers]);

  const dispatch = useDispatch();

  const timerValid = lives > 0 && seconds > 0 && gameStart;

  const newChallenge = () => {
    setIsIncorrect(false);
    setHaveToEnterAnswer(false);
    dispatch(restart());
  };

  const handleCount = () => {
    if (timerValid) {
      dispatch(loseTime());
    }
  };

  useEffect(() => {
    if (lives === 0 || seconds === 0) {
      dispatch(isFinished());
    }
  }, [lives, seconds]);

  useEffect(() => {
    let interval;
    if (timerValid) {
      interval = setInterval(() => {
        handleCount();
        if (lives === 0 || seconds === 0) {
          clearInterval(interval);
        }
      }, 1000);
    }
    return () => {
      clearInterval(interval);
    };
  }, [timerValid]);

  const submitHandler = () => {
    if (correctValue) {
      setGenerateNewNumbers(true);
      dispatch(gainPoints());
      dispatch(gainTime());
      setStreak(streak + 1);
      console.log(user);
    }

    if (+enteredValue === calculatedNums.result) {
      setCorrectValue(true);
    } else if (enteredValue.length === 0) {
      setHaveToEnterAnswer(true);
    } else {
      setIsIncorrect(true);
      dispatch(loseLife());
      setStreak(0);
    }
  };

  const inputValueHandler = (value) => {
    setIsIncorrect(false);
    setHaveToEnterAnswer(false);
    setEnteredValue(value);
  };

  const submitOrTryNewOne = () => {
    return correctValue ? "Try new one" : "Submit";
  };

  const goHome = () => {
    navigate("/");
    dispatch(restart());
  };

  return (
    <>
      <Navbar />

      {seconds && lives > 0 ? (
        <>
          <GameInfo />
          <Container component="main" maxWidth="xs">
            <Box
              sx={{
                marginTop: 8,
                display: "flex",
                flexDirection: "column",
                alignItems: "center",
              }}
            >
              <Typography>
                Fill in the box to make the equation true.
              </Typography>

              <Typography fontSize={28}>
                {operation !== "/"
                  ? `${calculatedNums.number1} ${operation} ${calculatedNums.number2}`
                  : `${calculatedNums.number2} ${operation} ${calculatedNums.number1}`}{" "}
                =
              </Typography>

              <TextField
                inputProps={{ inputMode: "numeric", pattern: "[0-9]*" }}
                type="number"
                name="sum"
                id="outlined-basic"
                label=""
                variant="outlined"
                onChange={(event) => {
                  inputValueHandler(event.target.value);
                }}
                disabled={correctValue}
                value={enteredValue}
              ></TextField>
              {haveToEnterAnswer && enterAnswer}
              {correctValue && correctAnswer}
              {isIncorrect && wrongAnswer}

              <Button
                type="button"
                sx={{ marginTop: 1 }}
                onClick={() => submitHandler()}
                variant="outlined"
              >
                {isIncorrect ? "Try again!" : submitOrTryNewOne()}
              </Button>
            </Box>
          </Container>
        </>
      ) : (
        <>
          <List
            sx={{
              marginTop: 8,
              display: "flex",
              flexDirection: "column",
              alignItems: "center",
            }}
          >
            <Typography fontSize={28}>GAME OVER</Typography>
            <Divider></Divider>
            <Typography sx={{ marginTop: 2 }} fontSize={28}>
              Final Score: {points}
            </Typography>
            <Divider></Divider>
            <Button
              sx={{ marginTop: 2 }}
              variant="contained"
              size="large"
              onClick={newChallenge}
            >
              New Challenge
            </Button>
            <Button
              sx={{ marginTop: 2 }}
              variant="contained"
              size="large"
              onClick={goHome}
            >
              Home Page
            </Button>
          </List>
        </>
      )}
    </>
  );
};

export default MainInput;

JsonWebTokenError: login working but CRUD not Working

I write a code for a sample project of an ecommerce web application. Everything is working fine like login, registration, admin dashboard. Reading from api is perfectly working. Every protected admin route is working absolutely fine with POSTMAN. But whenever I try to create, update or delete a product from the frontend it throws a error as below. Please help me solve

JsonWebTokenError: jwt must be provided
[0] at module.exports [as verify] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesjsonwebtokenverify.js:60:17)
[0] at requireSignIn (file:///C:/Users/Bangladesh%20One/Desktop/ReactJs/eCommerceApp/middlewares/authMiddleware.js:8:24)
[0] at Layer.handle [as handle_request] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterlayer.js:95:5)
[0] at next (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterroute.js:144:13)
[0] at Route.dispatch (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterroute.js:114:3)
[0] at Layer.handle [as handle_request] (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterlayer.js:95:5)
[0] at C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:284:15
[0] at Function.process_params (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:346:12)
[0] at next (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:280:10)
[0] at Function.handle (C:UsersBangladesh OneDesktopReactJseCommerceAppnode_modulesexpresslibrouterindex.js:175:3)

I tried with POSTMAN if my admin routes are working fine and I got positive result with POSTMAN.
But whenever I try to create, update, delete a product with frontend it throws error. But login , register is working fine

Here is my middleware

`import JWT from "jsonwebtoken";
import userModel from "../models/userModel.js";
import asyncHandler from "express-async-handler"

//Protected Routes token base
export const requireSignIn = async (req, res, next) => {
  try {
    const decode = JWT.verify(
      req.headers.authorization,
      process.env.JWT_SECRET
    );
    req.user = decode;
    next();
  } catch (error) {
    console.log(error);
  }
};

//admin acceess
export const isAdmin = async (req, res, next) => {
  try {
    const user = await userModel.findById(req.user._id);
    if (user.role !== 1) {
      return res.status(401).send({
        success: false,
        message: "UnAuthorized Access",
      });
    } else {
      next();
    }
  } catch (error) {
    console.log(error);
    res.status(401).send({
      success: false,
      error,
      message: "Error in admin middelware",
    });
  }
};`

Get Data from API – And Display

enter image description here
How to map the data inside choice
I used data.data.content.forEach to display other data. For choice how to do
Thank you

let formData1= ”;
data.data.content.forEach((user,index) => {
formData1 +=`

            <label for="inputEmail4">Type</label>
            <select class="custom-select mr-sm-2" id="typeSelect-${index + 1}" name="type">
                <option selected>Choose...</option>
                <option value="Multiple Choice">Multiple Choice</option>
                <option value="Email">Email</option>
                <option value="Short Text">Short Text</option>
              </select>
        </div>
        </div>

         
        <div class="form-group row justify-content-center">
            <div class="col-lg-6">
            <label for="inputEmail4">Question</label>
            <input type="text" name="question" value="${user.question}" class="form-control" id="question" placeholder="">
        </div>
        </div>
        <div id="choice-div" class="form-group row justify-content-center">
            <div class="col-lg-6">
            <label for="inputEmail4">Choice</label>
            <input type="text" class="form-control" id="choice" name="choice" placeholder="" value="${user.choice}">
        </div>
        </div>

})

I want to display the choice individually in html

waitForSelector timing out even tho the element is on screen

I’m building a checkout bot and I’m haveing truble geting past one of those dumb “enter your phonenumber for text” pop ups that sites do, the element I’m telling the bot to click is appering on screen but the bot wont click it. This is my first project ever on javascript and I have no Idea what I’m doing, I’m kinda taking the learn as you go aproach to coding right now and I’m learning a lot but Im really stuck here and I cant find what I am doing wrong.

async function regectingnumber(page) {
    try {
        console.log("Rejecting number")
        //await waitForTimeout(2000)
        //await page.setDefaultNavigationTimeout(60000);
        console.log("waiting...")
        await page.waitForSelector('button[class= css-10e85z4 errp0sa0]', {timeout:60000})
         console.log("waiting...")
         await page.evaluate(() => document.getElementsByClassName('button css-10e85z4 errp0sa0')[0].click());
        console.log("Number entered!");
        //await page.click('button[class="css-yq30jm e5ippug0"]');
        //console.log("Number rejected!");
    } catch (err) {
        console.error(err);
    }
}

this is just a small part of the code the part that im specifcally getting a error on because it wont let me post the full thing without calling it spam

Split array of objects to multiple arrays

I have an array like this :

[ { id: '1', quantity: 5 }, { id: '1', quantity: 5 }, { id: '1', quantity: 5 }, { id: '1', quantity: 3 }, { id: '2', quantity: 5 }, { id: '2', quantity: 5 }, { id: '2', quantity: 2 }, { id: '3', quantity: 5 }, { id: '3', quantity: 4 } ]

I want the result to be like this:
[ {products: [{id: 1, quantity: 5}, {id: 2, quantity: 5}, {id: 3, quantity: 5}]}, {products: [{id: 1, quantity: 5}, {id: 2, quantity: 5}, {id: 3, quantity: 4}]}, {products: [{id: 1, quantity: 5}, {id: 2, quantity: 2}]}, {products: [{id: 1, quantity: 3}]} ]

There should not be any duplicate IDs inside each products.

Thank you in advance.