how can i change the HTML pages using JS local

This is what i have seen in some other stackoverflow posts but none of them work and i get this error : Cannot GET /main%20page/index.html. How can i change the page to another local index.html

if (email.match(validEmailRegex) && password.match(validPasswordRegex)) {
  window.location.href = ('main page/index.html')
}

How do You Lazy Load Muliple Components/Pages at Once in React-Router

I am wondering how I can load muliple components at once, In my case these components are pages and I want if the user vists one of these pages then all the components/pages would load:)

Here is what I tried and you should get the jist of what I am trying to do here:

const [QuizProjectStart, QuizProjectQuestion, QuizProjectFinal, QuizError500] =
  lazy(() =>
    Promise.all([
      import("./featuredProjects/quizApp/pages/StartScreen"),
      import("./featuredProjects/quizApp/pages/QuestionScreen"),
      import("./featuredProjects/quizApp/pages/FinalScreen"),
      import("./featuredProjects/quizApp/pages/errors/Error500"),
    ])
  );

      <HashRouter>
        <Suspense
        fallback={<div>Loading...</div>}
        >
          <Routes>
            <Route element={<PortfolioHome />}>
              <Route path="/" element={<Navigate to="/home" />} />
              <Route path="/home" element={<Home title="Home" />} />
              <Route path="/error404" element={<Error404 title="ERROR" />} />
              <Route path="*" element={<Navigate to="/error404" />} />
            </Route>

            <Route
              path="/projects/todo"
              element={<ToDoProject title="Todo App" />}
            />

            <Route
              path="/projects/calculator"
              element={<CalculatorProject title="Calculator App" />}
            />

            <Route element={<QuizProject />}>
              <Route
                path="/projects/quiz"
                element={<QuizProjectStart title="Quiz App" />}
              />
              <Route
                path="/projects/quiz/gameStart"
                element={<QuizProjectQuestion title="Quiz App" />}
              />
              <Route
                path="/projects/quiz/gameEnd"
                element={<QuizProjectFinal title="Quiz App" />}
              />
              <Route
                path="/projects/quiz/error500"
                element={<QuizError500 title="ERROR" />}
              />
            </Route>
          </Routes>
        </Suspense>
      </HashRouter>

Mongoose pre-update document middleware – changed field is not written to database

Mongoose version 5.13.15

I am trying to set the value of fields (updatedBy, createdBy) on a document whenever it is written (created/updated).

As part of this endeavor, I have created the following test code to try to get it working

let currentUserId = '1';

const sampleSchema = new mongoose.Schema({
  color: String,
  createdBy: String,
  updatedBy: String,
});

sampleSchema.pre('save', async function() {
  console.log('save middleware called. This constructor:', this.constructor.name);
  let modifiedById = currentUserId;
  if (this.isNew) {
    this.createdBy = modifiedById;
  }
  this.updatedBy = modifiedById;
});

sampleSchema.pre('updateOne', {document: true, query: false}, async function() {
  console.log('updateOne middleware called. This constructor:', this.constructor.name);
  console.log('Setting `updatedBy` to ', currentUserId);
  this.updatedBy = currentUserId;
});

SampleModel = mongoose.model('sample', sampleSchema)

// Create
let sampleA = new SampleModel({color: 'black'});
let saved = await sampleA.save();
console.log('saved', saved);

// updateOne
currentUserId = '4';
await saved.updateOne({color: 'green'});
saved = await SampleModel.findOne({_id: saved._id});
console.log('saved 2', saved);

The output is as follows:

save middleware called. This constructor: model
saved {
  _id: 641cc720863a8421476a16ca,
  color: 'black',
  createdBy: '1',
  updatedBy: '1',
  __v: 0
}
updateOne middleware called. This constructor: model
Setting `updatedBy` to  4
saved 2 {
  _id: 641cc720863a8421476a16ca,
  color: 'green',
  createdBy: '1',
  updatedBy: '1',
  __v: 0
}

The output demonstrates that updateOne middleware is being called and the currentUserId value is as expected. The update sets the color field as expected to green but the updatedBy field remains unchanged. It should have been set to 4.

How do I set the value of a document field in the updateOne pre-save middleware?

How does the server confirm that a request from the client is being made by a certain user, with Google Sign In?

I’m developing a web game in JavaScript which communicates with a Node.js server that saves user data to a database, such as user levels, etc.

I want to use Google Sign In as a convenient way for logging players into the game. I only need their profile info and email.

I’ve got most of it working; I’m calling client = google.accounts.oauth2.initCodeClient(...) in the client, then when a user wants to sign in I retrieve the authorization code with client.requestCode(). My server receives the code, and I retrieve the tokens and user info with

  let { tokens } = await oauth2Client.getToken(req.body.code);
  oauth2Client.setCredentials(tokens);
  const userInfo = (
    await oauth2Client.verifyIdToken({
      idToken: tokens.id_token,
    })
  ).payload;

Now, I’m having trouble understanding how to proceed, so that the server can confirm that any further user requests com from a valid, logged in user. Do I send the access token to the client, which then sends it back to the server with any requests the user makes? What happens when the access token expires; how do I avoid having to ask the user to keep logging in each time they open the web app?

I’ve been reading Google’s documentation but I’m having a hard time understanding how the flow of this works in this situation. Any help is much appreciated.

So i have a huge json file and i want to create a smaller version of it where one of the values is based on 2 of the values from the main file

i have huge json file with array of objects i want to go throug that array and find a specific object then i want to return value based on 1 of its values.

heres is myfunction so far

async function getMatchData(matchId,summoner){
    
    const response = await fetch(`https://europe.api.riotgames.com/lol/match/v5/matches/${matchId}?api_key=`+key);
    
    var data = await response.json();
    
    let matchData= {
        victory:
        players: data.info.participants.map(element => obj = { team: element.teamId, champ: element.championName, champIcon: element.championName + '_0.jpg', summoner: element.summonerName, level: element.champLevel, build: { item1: element.item1, item2: element.item2, item3: element.item3, item4: element.item4, item5: element.item5, item6: element.item6, item0: element.item0 }, kills: element.kills, deaths: element.deaths, assists: element.assists, kda: (element.kills + element.assists) / element.deaths, cs: element.totalMinionsKilled + element.neutralMinionsKilled, victory: element.win })
    }
  
   return matchData;

and here is what relevant part of data would look like

"metadata": {
        "dataVersion": "2",
        "matchId": "EUW1_6324729398",
    },
    "info": {
        "gameCreation": 1679399513246,
        "gameDuration": 106,
        "gameEndTimestamp": 1679399729794,
        "gameId": 6324729398,
        "gameMode": "CLASSIC",
        "participants": [{
                "puuid": "REWcFv1LhXs4Yfkoq9iD0ENCdZT-dCA__ThUz0wZZ6pDbpQE95SRJpPZVFQbZXYiS4OR6IMHdBpBsA",
                "summonerId": "QbkQflR7yU5XsQRuDS59HuTW9vP_heQYZBCleFV92OvEWiyWSwOoRuqX1w",
                "summonerLevel": 88,
                "summonerName": "Pridestalker",
                "win": true
            },...]
        }

i want victory to be = data.info.participant.win where summonerName=summoner

Add as many text fields as I want and send it to mongodb

Under normal circumstances, I can write the data in the 2 text fields that I created at the beginning and send it to the db, but when I add a button next to the throw to Mongodb button (the button’s function is to add a new text field every time it is clicked), I cannot take the data from the new text fields there and assign Mongodb, can you help?

html:

<!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="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
        integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<style>
    .democlass {
        display: block;
        width: 100%;
        height: 34px;
        padding: 6px 12px;
        font-size: 14px;
        line-height: 1.42857143;
        color: #555;
        background-color: #fff;
        background-image: none;
        border: 1px solid #ccc;
        border-radius: 4px;
        margin-top: 10px;
        margin-bottom: 10px;
    }
</style>

<body>
    <h1>Posting data to mongo</h1>
    <form class="containter" method="post" action="/">
        <div class="form-group">
            <input class="form-control" name="title">
        </div>
        <div class="form-group">
            <input class="form-control" name="content">
        </div>
        <button>add mobgodb</button>
    </form>
    <button type="button" onclick="myFunction()">Click me</button>
    <form class="containter" method="post" action="/">
    <script>
        function myFunction() {
            var x = document.createElement("input");
            x.setAttribute("type", "text");
            x.setAttribute("name", "content2");
            x.setAttribute("class", "democlass");
            document.querySelector(".form-group").appendChild(x);
            const num = document.getElementById('input').value;
            console.log(num)
        }

    </script>
    </form>
    <script>src = "server.js"</script>
</body>

</html>

js file

const express = require('express');
const mongoose = require('mongoose');
const app = express();
const bodyParser = require("body-parser");

app.use(bodyParser.urlencoded({ extended: true }))

const url = //your mongodb's url;

mongoose.connect(url, { useNewUrlParser: true, useUnifiedTopology: true })
    .then((result) => console.log("Basarili"))
    .catch((err) => console.log(err))

const notesSchema = {
    title: String,
    content: String,
    conten2: String
}

const Note = mongoose.model("Note", notesSchema);

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

app.post("/", function(req, res) {
    let newNote = new Note({
        title: req.body.title,
        content: req.body.content,
        content2: req.body.content2
    });
    newNote.save();
    res.redirect('/');
})

app.listen(5500, function(){
    console.log("server is running on 5500");
})


if you have 2 text it works but i want add more text field and send all data to database

I create 2 text field and this datas send db

How to store a File object to local storage and retrieve it

I am converting a blob image to a File object, uploading to local storage and retrieving it, but when i retrieve it the file object isn’t in the format i expect.

I am converting a blob image to a file object like so:

async function convertBlobUrlToFile(image, filename, fileType) {
  const response = await fetch(image);
  const blobData = await response.blob();
  const uploadFileImage = new File([blobData], filename, { type: fileType });
  return uploadFileImage;
}

and uploading it to local storage like so:

convertBlobUrlToFile(croppedImage, imageFileName, fileType).then((blobObject) => {
        localStorage.setItem('croppedImage', blobObject);
 }).catch((error) => {
        console.error(error)
})

which looks like a normal file object, an example is


File {name: 'ProfilePic.jpg', lastModified: 1679604282406, lastModifiedDate: Thu Mar 23 
      2023 20:44:42 GMT+0000 (Greenwich Mean Time), webkitRelativePath: '', size: 600329, …}

however when i retrieve it, it just says
[object File]

I try to use JSON.parse to see if anything changes but i don’t have much luck.

Can someone help me in trying to store the File object into local storage correctly please so when i do localStorage.getItem() it is an actual File object like the example above.

Thank you for anyone helping 🙂

why built in method to getcurrentposition not working on my website

i put in a code to my browser and
this code working in my liveserver, but don’t wanna working on my website i have hosting from infinitefree:

    const bat = document.querySelector('.location')

    const geolocation = () => {



        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function (position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
              
                                var url = 'https://nominatim.openstreetmap.org/reverse?format=json&lat=' + latitude + '&lon=' + longitude;
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                       
                        const city = data.address.city;
                        const street = data.address.road                                    bat.innerHTML = ('City: ' + city) + '<br>' + ('Street: ' + street);

                    })
                    .catch(error => {
                        bat.innerText = ('Error:', error);
                    });
            });
        } else {
            bat.innerText = ('Geolocation is not supported by this browser');
        }
    }

    bat.addEventListener('click', geolocation)

how can i solve this problem

Joi: Validating an object containing a property whose value is an object with dynamic keys

I am attempting to create a response schema for a payload that looks something like this:

{
    ...
    property: {
        nestedProperty0: {
            'cd9d3cc3-de1d-4f89-a7d3-7bf6838481da': 'd73cb138-47be-4b7a-991b-f65e8981ae99'
        },
        nestedProperty1: {
            'beea88f8-38df-4faa-8e40-85d001edf754': '9dc4d536-7afa-446d-b4ff-e7d084bb2c43'
        }
    }
}

Where the keys and values of the nested properties are GUIDs, and the objects assigned to the nested properties can have one or many entries.

Currently, my schema looks something like this:

Joi.object({
    ...
    property: Joi.object({
        nestedProperty0: Joi.object().pattern(/wd/, Joi.string().guid()),
        nestedProperty1: Joi.object().pattern(/wd/, Joi.string().guid())
    })
})

This does not appear to be validating the payload correctly, complaining of additional properties.

How should I modify the schema to validate the nested properties correctly?

Change month to react date picker

When creating a custom header, functions are available to us increaseMonth() and decreaseMonth(). Is there any way to switch the month outside the header? As I understand it is impossible to implement scrolling. There was an idea to implement the change of the month through the wheel event on the calendar area.

I don’t know if this is possible, any ideas?

Uncaught (in promise) TypeError: Cannot set properties of null (setting ‘innerText’) [duplicate]

I’m trying to display the content from /terminal/input.txt in the div output.

HTML body:

<div className="events">
  <Navbar />
  <p id="output"></p>
  <Footer />
</div>

Javascript:

var output = document.getElementById('output');
var out;
fetch("/terminal/input.txt")
  .then(res => res.text())
  .then(data => {
    out = data;
  }).then(() => {
    output.innerText = out;
  });

ERROR: Uncaught (in promise) TypeError: Cannot set properties of null (setting 'innerText')

Can you please help me thanks in advance

Best method for converting an array of JSON

I have an array embedded in JSON, and i need to convert some elements over to another array in JSON. Is there a better method than iterating over the first to construct the second?

products = [{"name":"thing1","quantity":"1","price":11.52},{"name":"thing2","quantity":"1","price":1.28}]

items = [ {"product": "thing1", "quan": "1" }, {"product": "thing2", "quan": "1"} ] 

Basically, i need to convert products to items in the snippet above. My current approach is a for loop over products and create items. It feels clunky.

Thoughts?
Whats the best way to do this?

How to add a separator line to the sent mail?

Users can send mail to me in my application. Here is my code:

    const sendEmail = (text) => {
    const deviceId = "ad73f832h9214"
    const body = `${deviceId}nn${text}`
    const url = `mailto:[email protected]?subject=Support&body=${body}`;
    Linking.openURL(url);
}

I want to add a separator line between the device id and the message text as in the photo below. How can I do that?

enter image description here