Fetch after Fetch and waiting for res, second end point get empty req

i try to create a profile, that the imageid is saved inside the database, untill now all the code work good, the image upload work, and res good, and save the files.

but when i try to create a profile alawys the data i get to the createProfile Api
is undefined and cant be reached.

i have tried to use bodyParser,
json.stringtfy as in the code.

the other API work good. just when i try to use fetch inside fetch or pass with axios it alawys reach empty

this my html:

<!DOCTYPE html>
<html lang="en">
<head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
</head>
<body>
        <form id="createProfile" action="" method="POST" enctype="multipart/form-data">
                <p>profile name:</p>
                <input type="text" id="name" name="name">
                <p>image</p>
                <input type="file" name="image">
                <input type="submit" value="submit">
        </form>
</body>

</html>

this my js:

    const form = document.getElementById('createProfile')
    const name = document.getElementById('name')
    form.addEventListener('submit', async e => {
      e.preventDefault()
      const data = new FormData(form)

      console.log(...data)

      try {
        const res = await fetch('http://localhost:4000/api/uploadimage', {
          method: 'POST',
          body: data
        })

        const resData = await res.json()
        console.log(resData)

        if (resData.code === 200) {
          const resProfile = await fetch(
            'http://localhost:4000/api/createProfile',
            {
              method: 'POST',
              body: JSON.stringify({
                name: name.value,
                imageid: resData.imageid
              })
            }
          )
          const resProfileData = await resProfile.json()

          console.log(resProfileData.profileid + 'has been created')
        }
      } catch (err) {
        console.log(err.message)
      }
    })
  }

my end point of uploadimage:

exports.uploadimage = async function(req,res){

  if (req.file) {
    var imgsrc = './images/' + req.file.filename
    var insertData = "INSERT INTO images(image)VALUES(?)"

    connection.query(insertData,[imgsrc], (err,result)=>{
      if(err) throw err
      console.log("file uploaded")
      console.log(result.insertId);
      res.status(200).json({
        code:200,
        imageid:result.insertId,
        success:'image saved successfully'
      })

    } )
  } else {
    res.status(400).send("Please upload a valid image");
  }

}

my create profile end point:

exports.createProfile = async function ( req, res) {
  try {
    const requestedData = req.body;
    console.log(requestedData.name);
        
  } catch (err) {
    console.log(err.message);
  }
}

i have tried to use bodyParser,
json.stringtfy as in the code, use cors().

the other API work good. just when i try to use fetch inside fetch or pass with axios it always reach empty.

i just want to be able to get the request with data, and ill deal the rest.

thank you everyone for help.

Switch current “active” element

I have a button on my web-page. What I’m trying to achieve is: after the user clicks the button, I want the current “active” element to switch to the entire document, rather than the button (I’m sorry if I didn’t word it right).
Basically after the user clicks the button, if I hit the spacebar, the button gets pressed (which I mean as active). Instead, I want to de-activate the button once the button has been pressed so that the spacebar is detected on the document element, not the button.

I didn’t know what exactly to search up on the internet, and thus I’m asking this question here. My first approach was disabling the button after the click but that would make the button unusable later on.

Any help would be greatly appreciated!

What is this Javascript error message about?: TypeError: Cannot read properties of undefined (reading ‘id’)

I have created a React-Redux app that is currently working effectively, in the sense that it is able to call up an API to fetch, post, update and destroy as requested. Although the calls are carried out successfully, the page where the data is rendered is preceded by the following window, bearing an error message:

TypeError: Cannot read properties of undefined (reading 'id')
(anonymous function)
src/components/Journeymen.js:40
  
  39 |     {journeymen.map((journeyman) => (
> 40 |       <SwiperSlide key={journeyman.id} >
  41 |         <Link to={`/journeymen/${journeyman.id}`} className="text-decoration-none">

As soon as I close the error message window, however, I can see all the requested data rendered as expected, including the Journeyman.id itself, which the error message window had just told me was “undefined”. Can’t understand what is the issue.

This is the part of the Journeyman component that is pertinent:

  return (
    <div className="container">
      <h2 className="mt-3 mx-5">Journeymen</h2>
      <Swiper … lots of Swiper attributes listed here…>
        <div className="">
          {journeymen.map((journeyman) => (
            <SwiperSlide key={journeyman.id} >
              <Link to={`/journeymen/${journeyman.id}`} className="text-decoration-none">
                <div className="card my-3 mx-3">
                  <div className="">
                    <div className="my-3 mx-5">
                      <img className="" src={journeyman.image_url} width="150" height="150" alt="journeyman-img" />
                    </div>
                    <div className="my-3 mx-5">
                      <p className="text-secondary">
                        <strong>Id: </strong>
                        {journeyman.id}
                      </p>
                     …lots of other journeyman attributes rendered here
                    </div>
                  </div>
                </div>
              </Link>
            </SwiperSlide>
          ))}
        </div>
      </Swiper>
    </div>
  )

Can someone help me understand what is going on and how to resolve the matter? Thank you in advance.

Make part of the code a separate component of Next JS

I’m experimenting with Next 13 and routing it through the app directory. Now Next is trying to work mainly on the server, and because of this I have a problem.
I have a blog page that has a feature for uploading articles by clicking on a button. Since this function uses useState, this page needs to be made "use client", but the fact is that the service function {getAllPosts} is imported to this page that collects mdx files into an array of articles. This service function cannot be used together with “use client”. Next claim that it is normal practice to use "use client" in a separate component and import it to a page with server generation. Here is my code:

import { useState } from "react"

import Link from 'next/link'

import { getAllPosts } from '@/lib/getAllData'

export default function Blog() {

    /*loadmore*/
    const initialPostList = 2
    const incrementInitialPostList = 1;

    const [showPosts, setShowPosts] = useState(initialPostList);

    const handleLoadMore = () => {
        setShowPosts(showPosts + incrementInitialPostList)
    }

    const blogs = getAllPosts()

    return (
        <main className="flex flex-col">
            <h1 className="text-3xl font-bold">
                Мой блог
            </h1>


            <section className='py-10'>

                <div className='py-2'>
                    {blogs.slice(0, showPosts).map(blog => (
                        <Link href={'/blog/' + blog.slug} passHref key={blog.slug}>
                            <div className='py-2 flex justify-between align-middle gap-2'>
                                <div>
                                    <h3 className="text-lg font-bold">{blog.meta.title}</h3>
                                    <p className="text-gray-400">{blog.meta.description}</p>
                                </div>
                                <div className="my-auto text-gray-400">
                                    <p>{blog.meta.date}</p>
                                </div>
                            </div>
                        </Link>
                    ))}

                    {showPosts < blogs.length ? (
                        <div><button className="mainBtn loadBtn" onClick={handleLoadMore}>Больше статей</button></div>
                        ) : (
                        <div><button className="mainBtn loadBtn" disabled>Больше нет статей</button></div>
                    )}
                </div>
            </section>
        </main>
    )
}

The question is, how do I make a part of the above code a separate component? I’m not good at it at all. It is the code that is responsible for downloading articles:

/*loadmore*/
    const initialPostList = 2
    const incrementInitialPostList = 1;

    const [showPosts, setShowPosts] = useState(initialPostList);

    const handleLoadMore = () => {
        setShowPosts(showPosts + incrementInitialPostList)
    }


....


{showPosts < blogs.length ? (
                        <div><button className="mainBtn loadBtn" onClick={handleLoadMore}>More posts</button></div>
                        ) : (
                        <div><button className="mainBtn loadBtn" disabled>No posts</button></div>
                    )}

Thanks for the answers

Creating buttons using javascript API to fetch data and display the data

I’m using an API to display the names of players and details about the players. the buttons when clicked should show players’ information and the other button is supposed to remove a player from a roster list, but my buttons are not working correctly. I got one button to work, but it would only release the player’s information when it is supposed to show it. here’s my code:

const playerContainer = document.getElementById('all-players-container');
const newPlayerFormContainer = document.getElementById('new-player-form');


// Add your cohort name to the cohortName variable below, replacing the 'COHORT-NAME' placeholder
const cohortName = '2302-ACC-PT-WEB-PT-B';
// Use the APIURL variable for fetch requests
const APIURL = `https://fsa-puppy-bowl.herokuapp.com/api/${cohortName}/`;

/**
 * It fetches all players from the API and returns them
 * @returns An array of objects.
 */
const fetchAllPlayers = async () => {
    try {
        const response = await fetch(`https://fsa-puppy-bowl.herokuapp.com/api/${cohortName}/players`);
        const result = await response.json();
        const players = result.data.players;
        return players;
     } catch (err) {
        console.error('Uh oh, trouble fetching players!', err);
        return [];
       
    }
};

const fetchSinglePlayer = async (playerId) => {
    try {
        const response = await fetch(`https://fsa-puppy-bowl.herokuapp.com/api/${cohortName}/player/${playerId}`);
        const result = await response.json();
        const player = result.data.player;
        return player;
    } catch (err) {
        console.error(`Oh no, trouble fetching player # ${playerId} !`, err);
        return null;
    }
};

const addNewPlayer = async (playerObj) => {
    try {
        const response = await fetch(`https://fsa-puppy-bowl.herokuapp.com/api/${cohortName}/players`, {
            method: 'POST',
            headers: {
               'Content-Type' : 'application/json'
            },
            body: JSON.stringify({ player: playerObj })
        });
        const result = await response.json();
        return result.data.player;
        } catch (err) {
        console.error('Oops, something went wrong with adding that player!', err);
        return null;
    }
};

const removePlayer = async (playerId) => {
    try {
        const response = await fetch(`https://fsa-puppy-bowl.herokuapp.com/api/${cohortName}/player/${playerId}`, {
            method: 'DELETE'
           });
           const result = await response.json();
           return result.success;
           } catch (err) {
           console.error(`Whoops, trouble removing player #${playerId} from the roster!`, err);
           return false;
        }
  };

/**
 * It t akes an array of player objects, loops through them, and creates a string of HTML for each
 * player, then adds that string to a larger string of HTML that represents all the players. 
 * 
 * Then it takes that larger string of HTML and adds it to the DOM. 
 * 
 * It also adds event listeners to the buttons in each player card. 
 * 
 * The event listeners are for the "See details" and "Remove from roster" buttons. 
 * 
 * The "See details" button calls the `fetchSinglePlayer` function, which makes a fetch request to the
 * API to get the details for a single player. 
 * 
 * The "Remove from roster" button calls the `removePlayer` function, which makes a fetch request to
 * the API to remove a player from the roster. 
 * 
 * The `fetchSinglePlayer` and `removePlayer` functions are defined in the
 * @param playerList - an array of player objects
 * @returns the playerContainerHTML variable.
 */
const renderAllPlayers = (playerList) => {
    try {
        let playerContainerHTML = '';
        playerList.forEach((player) => {
            playerContainerHTML += `
        <div class="container">
         <div class="player-card">
          <img src="${player.imageUrl}" alt="${player.name}">
            <h2>${player.name}</h2>
            <p>${player.breed}</p>
            <p>${player.status}</p>
              <button class="details-button" data-player-id="${player.id}">See details</button>
              <button class="remove-button" data-player-id="${player.id}">Remove from roster</button>
          </div>
        </div>`;
        });
        playerContainer.innerHTML = playerContainerHTML;
        // Add event Listeners to the buttons in each player card
        const seeDetailsBtns = document.querySelectorAll('.details-button');
        const removeFromRosterBtns = document.querySelectorAll('.remove-button');
/*See Details button functionality,
 To be able to see the details about player*/
         seeDetailsBtns.forEach((btn) => {
            btn.addEventListener('click', async (event) => {
                const playerId = event.target.dataset.playerId;
                const player = await fetchSinglePlayer(playerId);
                console.log(player);
            

        
               });
        
            });
        
         removeFromRosterBtns.forEach((btn) => {
           btn.addEventListener('click', async (event) => {
                const playerId = event.target.dataset.playerId;
                const success = await removePlayer(playerId);
                console.log(success);
             });
           });
  
        } catch (err) {
        console.error('Uh oh, trouble rendering players!', err);
    }
};


/**
 * It renders a form to the DOM, and when the form is submitted, it adds a new player to the database,
 * fetches all players from the database, and renders them to the DOM.
 */
const renderNewPlayerForm = () => {
    try {
        // Create the form element
        const newPlayerForm = document.createElement('form');

        // Add form elements (input fields, buttons, etc) to the form element

        // Add an event Listener to the form submission
            newPlayerForm.addEventListener('submit', async (event) => {
               event.preventDefault();
            
            // retrieve form data
            const formData = new FormData(newPlayerForm);
            await addNewPlayer(Object.fromEntries(formData));


            // send request to add the new player to the database
            const players = await fetchAllPlayers();

            // render all players to the DOM
            renderAllPlayers(players);

            // Clear the for
            newPlayerForm.reset();
       });

         // Append the form to the DOM
        newPlayerFormContainer.appendChild(newPlayerForm);

``your text``catch (err) {
        console.error('Uh oh, trouble rendering the new player form!', err);
    }
}

const init = async () => {
    const players = await fetchAllPlayers();
    renderAllPlayers(players);
    renderNewPlayerForm();
}

init();

I need to create a database where people’s opinions about specific products are stored

I created a website basically using html, css and javascript (I learned to program 2-3 months ago)

Looking around the internet, I think the best way to create a serial database using postgreSQL

When a person fills in the form and sends it, it’s like creating a new line in the postgreSQL table where everything would be grouped.

I was in doubt of how I would link the product image in the table or if there was any other better way, perhaps storing the image in another postgreSQL location that allows the javascript to bring the image based on the product name.

I created this post to find out if this is the best way for my idea.

I’m not looking for an easier way, I just think that by learning to use postgreSQL, maybe in the future I’ll find an easier job because I know how to use it

I’m learning to use PostgreSQL, so I haven’t implemented it on my site yet or anything like that

k6.io test could not find import java script

Would you please tell what is correct way of ‘folder’ reference/path in VisualStudioCode?

I have folders in the root dir:

  • data -> createNode.js
  • tests -> createNodeTests.js

and wants to import some .js files in the tests folder, but it fails to find the imported

k6 run -u 1 -d 1s createNodeTests.js --http-debug="full"

          /      |‾‾| /‾‾/   /‾‾/
     /  /       |  |/  /   /  /
    /  /        |     (   /   ‾‾
   /             |  |   |  (‾)  |
  / __________   |__| __ _____/ .io

WARN[0000] The moduleSpecifier "createNodeTests.js" has no scheme but we will try to resolve it as remote module. This will be deprecated in the future and all remote modules will need to explicitly use "https" as scheme.
ERRO[0000] The moduleSpecifier "createNodeTests.js" couldn't be found on local disk. Make sure that you've specified the right path to the file. If you're running k6 using the Docker image make sure you have mounted the local directory (-v /local/path/:/inside/docker/path) containing your script and modules so that they're accessible by k6 from inside of the container, see https://k6.io/docs/using-k6/modules#using-local-modules-with-docker. Additionally it was tried to be loaded as remote module by prepending "https://" to it, which also didn't work. Remote resolution error: "Get "https://createNodeTests.js": dial tcp: lookup createNodeTests.js: no such host"

enter image description here

How to split a text after … ?

I want to split a text when a headline was found.

The headline always starts with <p><strong> and ends with </strong></p>.

The text between are always different.

<p><strong>Omnis officiis qui hic mollitia<br /><br /></strong></p>

<p><span style="font-weight: 400;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit mollitia cupiditate ab eaque exercitationem. Omnis officiis qui hic mollitia molestiae eveniet porro ducimus sint? Sint sapiente quibusdam alias dolor a voluptatem, minus velit placeat fugit. Eum nulla omnis eaque dicta!</span></p>

<p><strong>Quibusdam alias dolor a</strong></p>

<p><span style="font-weight: 400;">Hic mollitia molestiae eveniet porro ducimus sint? Sint sapiente quibusdam alias dolor a voluptatem, minus velit placeat fugit. Eum nulla omnis eaque dicta!</span></p>
<ul><li style="font-weight: 400;">Ducimus sint</li><li style="font-weight: 400;">Ducimus sint</li><li style="font-weight: 400;">Ducimus sint</li><li style="font-weight: 400;">Ducimus sint</li></ul>

<p><strong>Lorem ipsum dolor sit amet</strong></p>

<p><span style="font-weight: 400;">Assumenda aspernatur sit, cumque autem in suscipit laudantium natus, dolore, non molestiae optio alias reiciendis cum. Asperiores autem doloribus repellendus minima eaque? Earum iure inventore minima soluta ex vitae nostrum, aut nulla enim maxime rerum doloremque aperiam commodi! Numquam, nemo commodi! Consequuntur nulla sint dolorem itaque eveniet veritatis repellat? Saepe dignissimos esse vero? Impedit reprehenderit officiis beatae blanditiis</span></p>

In my example i want to get this result:

[
    0: "<p><span style="font-weight: 400;">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit mollitia cupiditate ab eaque exercitationem. Omnis officiis qui hic mollitia molestiae eveniet porro ducimus sint? Sint sapiente quibusdam alias dolor a voluptatem, minus velit placeat fugit. Eum nulla omnis eaque dicta!</span></p>",
    1: "<p><span style="font-weight: 400;">Hic mollitia molestiae eveniet porro ducimus sint? Sint sapiente quibusdam alias dolor a voluptatem, minus velit placeat fugit. Eum nulla omnis eaque dicta!</span></p><ul><li style="font-weight: 400;">Ducimus sint</li><li style="font-weight: 400;">Ducimus sint</li><li style="font-weight: 400;">Ducimus sint</li><li style="font-weight: 400;">Ducimus sint</li></ul>",
    2: "<p><span style="font-weight: 400;">Assumenda aspernatur sit, cumque autem in suscipit laudantium natus, dolore, non molestiae optio alias reiciendis cum. Asperiores autem doloribus repellendus minima eaque? Earum iure inventore minima soluta ex vitae nostrum, aut nulla enim maxime rerum doloremque aperiam commodi! Numquam, nemo commodi! Consequuntur nulla sint dolorem itaque eveniet veritatis repellat? Saepe dignissimos esse vero? Impedit reprehenderit officiis beatae blanditiis</span></p>"
]

How i can get this result?

How can i find the xpath of a keyword when searching a webpage in in python using javascript

I’m trying to find the xpath of keyword that i search on a webpage with javascript. This code is in python but you can use javascript to search the webpage

This is how i search. True if found False if not found. It’s working find for me.

found_or_not_keyword_1 = driver_global.execute_script(f"return window.find('{keyword_1}', false, true, true);")
    found_or_not_keyword_2 = driver_global.execute_script(f"return window.find('{keyword_2}', false, true, true);")
    found_or_not_keyword_3 = driver_global.execute_script(f"return window.find('{keyword_3}', false, true, true);")

I tried this and it always returns none for something that it found.

keyword_1_xpath= driver_global.execute_script("document.evaluate('.//text()[contains(., "" + keyword_1 + "")]', document, null, XPathResult.ANY_TYPE, null).iterateNext();")
print(f"keyword_1_xpath{keyword_1_xpath}")

keyword_2_xpath= driver_global.execute_script("document.evaluate('.//text()[contains(., "" + keyword_2 + "")]', document, null, XPathResult.ANY_TYPE, null).iterateNext();")
print(f"keyword_2_xpath{keyword_2_xpath}")

keyword_3_xpath= driver_global.execute_script("document.evaluate('.//text()[contains(., "" + keyword_3 + "")]', document, null, XPathResult.ANY_TYPE, null).iterateNext();")
print(f"keyword_3_xpath{keyword_3_xpath}")

is there a way of reversing events and creating new ones with jquery when dealing with event listeners

I’m creating a navbar with multiple dropdowns and using jquery, each has an event listener which closes and opens them. I then added an overlay to cover the background when a dropdown is open. The overlay works as expected but the problem is, when i click the item to open the dropdown, the overlay opens well until i click the next element, then the overlay starts behaving unexpectedly ie. i click first item, overlay opens, i click the next, it closes and keeps doing that for every item i click. basically it reverses the order. I’ve spent the whole day on the internet, asked even chatgpt, bard and bingchat and its still problematic. Here is the my code.

<div id="cn-overlay" class="cn-overlay"></div>

<div class="bottom-nav">
    <div class="bottom-nav-wrapper">
        <ul id="dropdown-wrapper">
            <li class="bottom-nav-link dropdown">
                <a class="link-title">
                    tv
                    <i class="fa-solid fa-angle-down"></i>
                </a>
                <div class="hide">
                    <ul>
                        <li><a href="#!">samsung</a></li>
                        <li><a href="#!">sony</a></li>
                        <li><a href="#!">jvc</a></li>
                        <li><a href="#!">star</a></li>
                        <li><a href="#!">pine</a></li>
                        <li><a href="#!">lg</a></li>
                    </ul>
                </div>
            </li>
            <li class="bottom-nav-link dropdown">
                <a href="#!" class="link-title">
                    others
                    <i class="fa-solid fa-angle-down"></i>
                </a>
                <div class="hide">
                    <ul>
                        <li><a href="#!">x-box</a></li>
                        <li><a href="#!">speakers</a></li>
                    </ul>
                </div>
            </li>
            <li class="bottom-nav-link dropdown">
                <a href="#!" class="link-title">
                    phones
                    <i class="fa-solid fa-angle-down"></i>
                </a>
                <div class="hide">
                    <ul>
                        <li><a href="#!">huawei</a></li>
                        <li><a href="#!">oppo</a></li>
                        <li><a href="#!">iphone</a></li>
                        <li><a href="#!">samsung</a></li>
                    </ul>
                </div>
            </li>
            <li class="bottom-nav-link dropdown">
                <a href="#!" class="link-title">clothes<i class="fa-solid fa-angle-down"></i></a>
                <div class="hide">
                    <ul>
                        <li><a href="#!">socks</a></li>
                        <li><a href="#!">jumpers</a></li>
                        <li><a href="#!">sweaters</a></li>
                        <li><a href="#!">shirts</a></li>
                    </ul>
                </div>
            </li>
        </ul>
    </div>

</div>
/* overlay */
.cn-overlay {
    width: 100%;
    height: calc(100% - 80px);
    background-color: rgba(0, 0, 0, 0.6);
    position: fixed;
    /* top: 0; */
    left: 0;
    bottom: 0;
    right: 0;
    opacity: 0;
    /* display: none; */
    visibility: hidden;
    transition: all .3s ease;
    z-index: 2;
    pointer-events: none;
}

/* Class added to the overlay via JavaScript to show it when navigation is open */
.cn-overlay.on-overlay {
    opacity: 1;
    visibility: visible;
}
div.bottom-nav-wrapper{
    height: 40px;
}

div.bottom-nav-wrapper ul {
    display: flex;
    z-index: 10;
}

div.bottom-nav-wrapper ul li {
    padding: 10px;
    user-select: none;
}

div.bottom-nav-wrapper ul li a i{
    font-size: 12px
}

li.bottom-nav-link div {
    position: absolute;
    width: 50%;
    height: 50%;
    left: 0;
    right: 0;
    margin-inline: auto;
    margin-top: 10px;
    /* backdrop-filter: blur(100px); */
}

li.bottom-nav-link div ul {
    display: grid;
    grid-template-columns: 200px 200px;
}

/* li.bottom-nav-link div ul li{
    /* display: flex; 
    align-items: center;
} */

li.bottom-nav-link .link-title {
    font-size: 1em;
    font-weight: 700;
    text-transform: uppercase;
    line-height: 18px;
    text-align: center;
    font-family: montserrat;
}

li.bottom-nav-link div a {
    display: flex;
    align-items: center;
    justify-content: start;
    gap: 10px;
}

.hide {
    display: none;
    /* background-color: rgba(0, 0, 0, .9); */
    background-color: var(--md-sys-color-on-surface);
}
var isDropdownOpen = false;

$(document).ready(function () {
    // If a link has a dropdown, add sub menu toggle.
    $('.dropdown a:not(:only-child)').click(function (e) {
        $(this).siblings('.hide').slideToggle();
        isDropdownOpen = !isDropdownOpen
        if (isDropdownOpen) {
            $('#cn-overlay').addClass('on-overlay'); // Show the overlay
        }
        else {
            $('#cn-overlay').removeClass('on-overlay'); // Hide the overlay
        }
        // Close one dropdown when selecting another
        $('.hide').not($(this).siblings()).hide();
        e.stopPropagation();
    });

    // Clicking away from dropdown will remove the dropdown class
    $(document).on('click', function (e) {
        if (!$(e.target).closest('.dropdown').length) {
            $('.hide').hide();
            $('#cn-overlay').removeClass('on-overlay');// Hide the overlay
            isDropdownOpen = !isDropdownOpen
        }
    });
});

I added the isDropdownOpen and if statement later to try and check whether it is open to close the overlay but the problem persisted. Ive added and removed so many lines of code i can barely remember them. I thought of trying to make the overlay revert to previous values then redoing it, hence the poorly worded question but i cant quite figure it out.

Displaying dynamic data from an csv file

I’m using Selenium and Python to scrape the 1s eth price from Binance. The Scraper is getting the 1s price and storing it in an csv file. My goals is to display the data which is constantly being updated in the csv file to be updated in an simple html page. Pretty much like Binance is doing it, but simpler. For some reason the index page updates, but the p tag doesn’t update with the data in the csv file. I think the problem is with my JavaScript. I guessing It’s not getting the data because it can’t recognize my Python file or read it.

This is my Index file which includes Javascript. Just a some basic hmtl and some JavaScript that should get the data from the csv file and update it every 1s, but doesn’t

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <h1>Lorem ipsum dolor sit amet.</h1>

    <p id="eth_eur_1s">0</p>

    <script>
        function startLiveUpdate () {
            
            const ethPrice = document.getElementById('eth_eur_1s');


            setInterval(function() {
                fetch('Etherium_USDT_1s.csv').then(function (response) {

                    return response.json();

                }) .then(function (data) {

                    ethPrice.textContent = data.eth_eur_1s;

                }) .catch(function(error){

                    console.log("Error");

                });

            }, 1000);
            
            
        }

        document.addEventListener('DOMContentLoaded', function() {

            startLiveUpdate();

        });

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

This is my Python file. Just gets the 1s price from the Binance and prints it to my empty csv file.

import os
import time
import pandas
from selenium import webdriver 
from selenium.webdriver.chrome.options import Options

options = Options() 
options.add_argument("--headless=new") 


os.environ['PATH'] += r"C:/SeleniumDrivers" # path to driver
driver = webdriver.Chrome(options=options) 
driver.get("https://www.binance.com/en/trade/ETH_USDT?_from=markets&theme=dark&type=spot") 

eth_price = []


while True: 
    
    price = driver.execute_script("""
      return document.querySelector('.showPrice').innerText
    """)
    
    eth_price.append(price)
    
    df = pandas.DataFrame({'eth_price':eth_price})
    
    df.to_csv('Etherium_USDT_1s.csv', index=False)
    time.sleep(1)
    print(df)

I know It’s possible through ajax or something that can use dynamic information, but I just need some guidance on how. I appreciate any help 🙂 Thanks

User How can I grab the CAPTCHA image that changes every time it is reloaded or when I send a GET request,without taking a screenshot?

I have a CAPTCHA on a login page and I want to capture that CAPTCHA using Selenium, javascript or any other possible method.
The CAPTCHA element is displayed as

<img src="https://rds3.northsouth.edu/index.php/captcha">.

However, the CAPTCHA image changes every time I reload or download the CAPTCHA from the link: https://rds3.northsouth.edu/index.php/captcha.how can i get the exact image that is displayed ad it is on the page?

I tried using the following code to grab the CAPTCHA image:


captcha_img = chrome_driver.find_element_by_xpath('//img[@id="captcha-img"]')
captcha_img_url = captcha_img.get_attribute('src')
response = requests.get(captcha_img_url)
if response.status_code == 200:
    # Save the image to a file
    with open('captcha.png', 'wb') as f:
        f.write(response.content)

However, this method does not work because the CAPTCHA image changes every time a new request is sent, and the link provides a new CAPTCHA image. But I want to capture the displayed image for OCR purposes without taking a screenshot of the element. So how can i get the exact image that is displayed ad it is on the page?

useGlobalPipes and useStaticAssets in Nestjs

When I create an application using nestjs I have come across some weird problem.

When I create an application without type useStaticAssets method is not working:

const app = await NestFactory.create(AppModule);
  app.useGlobalPipes(
    new ValidationPipe({
      whitelist: true,
    }),
  );

  app.useStaticAssets(join(process.cwd(), 'uploads')); --> Property 'useStaticAssets' does not exist on type 'INestApplication'

But when I use type annotation useStaticAssets is working but useGlobalPipes method is not working:

const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.useGlobalPipes(.         // --> Property 'useGlobalPipes' does not exist on type 'NestExpressApplication'
    new ValidationPipe({
      whitelist: true,
    }),
  );

  app.useStaticAssets(join(process.cwd(), 'uploads'));

I dont know what to do?

When I use whether type, both methods should work