Get requested URL with params

I’m doing an API request with some params.

Example:

import Axios from 'axios';

const generator = Axios.create({
    baseURL: "https://some-api.com"
});

// Calling the API with GET method.
generator.get('/some/endpoint/', {
   params: {
      user: "user-test",
      password: "password-test"
   }
})

Can I get the entire URL, including the params? In this case, the answer to my question would be: “https://some-api.com/some/endpoint&user=user-test&password=password-test”.

Here I’m just mocking the params, but in my real application, it’s dynamic.

Why is website not working on a live server?

I have built a website on Node.js, using Handlebars and Express.js connecting to MongoDB.
I am not sure why after I have uploaded it to the live hosting server it just show Files Directory..
Here is the snippet of what I see:
what i see right now on the live server

I understand I think that it is looking for index.html but I use templating Handlebars and my entry point is index.js as I stated in package.json here:
enter image description here

IO is not defined [duplicate]

I’m working on a web app that uses socket.io for client to server communication.
When I run the site, in the inspect tab it gives me Uncaught ReferenceError: io is not defined at script.js:1 (anonymous) @ script.js:1
Here is my HTML:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Hack.top - Sign Up</title>
    <link href="../style.css" rel="stylesheet" type="text/css">
  </head>
    

    <body>

        <nav>
            <a href="/" class="first">
                <div class='title-container'><h3>Hack.top</h3><h3 id='title-underscore'>&#95;</h3></div>
            </a>

            <div class="links">
                <a href="">learn more</a>

                <a href="">competitions</a>

                <a href="">contact</a>

                <!-- <a href="/signup">
                    <button>sign up</button>
                </a> -->
            </div>
        </nav>

        <main>
            <div class="info signup">
                <h3>Hello!</h3>
                
                <p>Sign up to start hacking.</p>

        <input type="email" placeholder="[email protected]" id="email">

                <input type="text" placeholder="Username" id="username">

                <input type="password" placeholder="Password" id="password">
                
                <input type="password" placeholder="Confirm password" id="confirmPassword">

                <p>Already have an account? <a href="/login">log in</a></p>

                <button id="signUpButton">sign up</button>
            </div>
        </main>


        <script src="../script.js"></script>
    <script src="/socket.io/socket.io.js"></script>
  </body>
</html>

And my client-side JS:

socket = io();

socket.on('logged', function (res){
  if(res.err){
    //res.message...
  } else {
  
  }
});

document.getElementById("signUpButton").addEventListener("click", createAccount);

function login(){
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;

  const user = {
    'username': username,
    'password': password
  }
  
  socket.emit('login', user);
}


function createAccount(){
  const email = document.getElementById('email').value;
  const username = document.getElementById('username').value;
  const password = document.getElementById('password').value;
  const confirmPassword = document.getElementById('confirmPassword').value;

  if(password != confirmPassword){
    //alert user
  }

  const user = {
    'username': username,
    'password': password,
    'email': email
  }

  socket.emit('createAccount', user);
}

I don’t think server side JS is necessary for this issue but if someone needs to see just ask and I’ll add it.
Not sure why this is happening, thanks.

I need more understanding to api and local servers

I’m new to using APIs, i have learned to build a localhost server and route post and get. Then i watched a tutorial on YouTube where the author didn’t build a local server but just used the api in js file and it worked so it made me confused about the usage of servers with api!

Scripts not showing up in wordpress theme

I added these scripts to the header and footer of the theme I’m working on:

<!DOCTYPE html>
<html>
    <head>
        <?php wp_head();?>
        
    </head>
<body <?php body_class();?>>
<?php wp_footer();?>

</body>
</html>

In functions.php, I also added:

<?php

function load_stylesheets()
{
    wp_register_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), false, 'all');
    wp_enqueue_style('bootstrap');

    wp_register_style('stylesheet', get_template_directory_uri() . '/style.css', array(), false, 'all');
    wp_enqueue_style('stylesheet');
}
add_action('wp_enqueue_scripts', 'load_stylesheets');

function include_jquery()
{
    wp_deregister_script('jquery');
    wp_enqueue_script('jquery', get_template_directory_uri() . '/js/jquery.min.js', '', 1, true);
    add_action('wp_enqueue_scripts', 'jquery');
}
add_action('wp_enqueue_scripts', 'include_jquery');

function load_js()
{
    wp_register_script('customjs', get_template_directory_uri() . '/js/scripts.js', '', 1, true);
    wp_enqueue_script('customjs');
}

add_action('wp_enqueue_scripts', 'load_js');

When I inspect the local site, I don’t see these scripts or any other scripts I enqueued in functions.php. Only scripts I could find:

<script type="text/javascript">
            window._wpemojiSettings = {"baseUrl":"https://s.w.org/images/core/emoji/13.1.0/72x72/","ext":".png","svgUrl":"https://s.w.org/images/core/emoji/13.1.0/svg/","svgExt":".svg","source":{"concatemoji":"http://localhost/financeblog/wp-includes/js/wp-emoji-release.min.js?ver=5.8.2"}};
            !function(e,a,t){var n,r,o,i=a.createElement("canvas"),p=i.getContext&&i.getContext("2d");function s(e,t){var a=String.fromCharCode;p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,e),0,0);e=i.toDataURL();return p.clearRect(0,0,i.width,i.height),p.fillText(a.apply(this,t),0,0),e===i.toDataURL()}function c(e){var t=a.createElement("script");t.src=e,t.defer=t.type="text/javascript",a.getElementsByTagName("head")[0].appendChild(t)}for(o=Array("flag","emoji"),t.supports={everything:!0,everythingExceptFlag:!0},r=0;r<o.length;r++)t.supports[o[r]]=function(e){if(!p||!p.fillText)return!1;switch(p.textBaseline="top",p.font="600 32px Arial",e){case"flag":return s([127987,65039,8205,9895,65039],[127987,65039,8203,9895,65039])?!1:!s([55356,56826,55356,56819],[55356,56826,8203,55356,56819])&&!s([55356,57332,56128,56423,56128,56418,56128,56421,56128,56430,56128,56423,56128,56447],[55356,57332,8203,56128,56423,8203,56128,56418,8203,56128,56421,8203,56128,56430,8203,56128,56423,8203,56128,56447]);case"emoji":return!s([10084,65039,8205,55357,56613],[10084,65039,8203,55357,56613])}return!1}(o[r]),t.supports.everything=t.supports.everything&&t.supports[o[r]],"flag"!==o[r]&&(t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&t.supports[o[r]]);t.supports.everythingExceptFlag=t.supports.everythingExceptFlag&&!t.supports.flag,t.DOMReady=!1,t.readyCallback=function(){t.DOMReady=!0},t.supports.everything||(n=function(){t.readyCallback()},a.addEventListener?(a.addEventListener("DOMContentLoaded",n,!1),e.addEventListener("load",n,!1)):(e.attachEvent("onload",n),a.attachEvent("onreadystatechange",function(){"complete"===a.readyState&&t.readyCallback()})),(n=t.source||{}).concatemoji?c(n.concatemoji):n.wpemoji&&n.twemoji&&(c(n.twemoji),c(n.wpemoji)))}(window,document,window._wpemojiSettings);
        </script>

Failed to POST: Post “http://localhost:3000/webhook”: context deadline exceeded (Client.Timeout exceeded while awaiting headers)

I have this error when I run stripe listen --forward-to localhost:3000/webhook on cmd and server on hyperterminal.
[stripe listen –forward-to localhost:3000/webhook][1]

I basically copied and pasted from the document so I’m not sure what is the problem
[1]: https://i.stack.imgur.com/iosZa.png
[2]: https://i.stack.imgur.com/Wk0xY.png

const stripe = require("stripe")(process.env.STRIPE_PRIVATE_KEY);
const bodyParser = require("body-parser");
const app = express();

app.post('/webhook', bodyParser.raw({type: 'application/json'}), (request, response) => {
  const payload = request.body;

  console.log("Got payload: " + payload);

  response.status(200);
});

Add class to an input when its focused, and remove it when isnt focused

I’m trying to add the class “.contact__form-input–focused” to the input that is focused from a form.

I’m trying to do that adding an event listener to every input, and then if it has the class already delete that class from the classlist.

//INPUT ANIMATION
const input = document.querySelectorAll("contact__form-input");

function addClass(input) {
  input.classList.add("contact__form-input--focused");
}

function removeClass(input) {
  input.classList.remove("contact__form-input--focused");
}

for (let i = 0; i < input.length; i++) {
  if (item[i].classList.contains("contact__form-input--focused")) {
    item.addEventListener("focus", addClass(input[i]));
  } else {
    item.addEventListener("blur", removeClass(input[i]));
  }
}
.contact__form {
  display: flex;
  flex-direction: column;
}

.contact__form-input {
  border: none;
  border-bottom: .1rem solid rgba(0, 0, 0, .12);
  font-size: var(--medium-font-size);
  margin: 0;
  padding: 4px 0;
  width: 100%;
  background: 0 0;
  text-align: left;
  color: inherit;
}

.contact__form-input--focused {
  /*some animations here*/
}
<form class="contact__form" method="POST">
  <label class="contact__form-label">
            <span>Name</span>
            <input class="contact__form-input" name="Name" type="text" autocomplete="name" required>
          </label>
  <label class="contact__form-label">
            <span>Phone number</span>
            <input class="contact__form-input" name="Phone number" type="tel" autocomplete="tel" required>
          </label>
  <label class="contact__form-label">
            <span>Message</span>
            <input class="contact__form-input" type="text" required>
          </label>
  <button class="contact__form-button">Send</button>
</form>

Blob video stream not showing on iOS when receiving a stream from socket.io (JavaScript and Node.js)

This works perfectly fine on android (every part of it). But when I receive a video stream wrapped in a blob on iOS from android or another iOS device, it does not show any sign of loading the video or displaying it. However, when I show my own video to myself on iOS, it works.

I have tried the following:

video.setAttribute('autoplay', '');
video.setAttribute('playsinline', '');
video.setAttribute('muted', '');

Or adding a source element to the video element, but these did not work.

How am I supposed to fix the receiving video issue on iOS?

Code (sorry for all the styling):

Client:

let media;
const done = document.getElementById('done');
const vidCon = document.getElementById('video-con');
var getUserMedia = (navigator.mediaDevices.getUserMedia || navigator.mediaDevices.webkitGetUserMedia || navigator.mediaDevices.mozGetUserMedia).bind(navigator.mediaDevices);
    getUserMedia({
        video: true,
        audio: true
    }).then((stream) => {
        const myVideo = document.createElement('video');
        myVideo.srcObject = stream;
        myVideo. setAttribute('autoplay', '');
        myVideo. setAttribute('muted', '');
        myVideo. setAttribute('playsinline', '');
        myVideo.style.width = '100%';
        myVideo.style.height = '80%';
        myVideo.muted = true;
        myVideo.style.display = 'block';
        myVideo.style.objectFit = 'cover';
        media = new MediaRecorder(stream); 
        media.onstart = function(e) {
        this.chunks = [];
        myVideo.play();
        document.getElementById('video-base-con').append(myVideo);
    }
    done.onclick = function() {
        media.stop();
        audio.src = "93642-Blakes_7_Gun_144bpm.wav";
        audio.play();
        audio.addEventListener('ended', go);
        done.style.display = 'none';
        document.getElementById('blank-choosing').style.display = 'block';
    }
    media.ondataavailable = function(e) {
        this.chunks.push(e.data);
    }
    media.onstop = function(e) {
        myVideo.remove();
        var blob = new Blob(this.chunks, { 'type' : 'video/ogg; codecs=opus' });
        socket.emit('send-video', blob);
    }
});
socket.on('recieve-video', (stream, codeNew) => {
            if (codeNew == code.value) {
                document.getElementById('blank-video').style.display = 'none';
                console.log('recieved video.');
            const blob = new Blob([stream], { 'type' : 'video/ogg; codecs=opus' });
            const video = document.createElement('video');
            video.src = window.URL.createObjectURL(blob);
                                video. setAttribute('autoplay', '');
video. setAttribute('muted', '');
video. setAttribute('playsinline', '');
            vidCon.style.display = 'block';
            video.style.width = '90%';
            video.style.height = '100%';
            video.style.objectFit = 'cover';
            vidCon.style.width = '100%';
            vidCon.style.height = '100%';
            vidCon.style.textAlign = 'center';
            vidCon.style.backgroundColor = 'lightgray';
            vidCon.style.borderRadius = '30px';
            vidCon.append(video);
            video.play();
            video.addEventListener('ended', () => {
                video.remove();
                vidCon.style.display = 'none';
                answers.style.display = 'block';
            }, false);
            }
        });

Server:

socket.on('send-video', (blob) => {
     socket.broadcast.emit('recieve-video', blob, code); 
});

Thanks in advance!

Reactjs creates infinite loop using setTimeout

Here is my App.js that contains beside Header and the MainView
an AlertDialog. Alert dialog has two state controlled props:

msg={alertMsg} toggleClass={alertToggleClass}

The task of AlertDialog is to show if the className is “alertDlg” and disappear if it’s “alertDlg alertDlgClosed”. Testing it via the inspector manually (changing className) shows, that it works fine.

Therefore alertToggleClass is set to “alertDlg alertDlgClosed” when initializing, so that the alert dialog is hided by default.

Within the MainView Component (before render())
sendGlobalAlert("Test Alert Msg") gets called which is simply a callback to the showAlert(msg) method in App.js.

Now here goes the tricky part: calling setAlertToggleClass("alertDlg"); in showAlert(msg)-method shows the custom alert dialog as expected. However trying to disable it by calling setAlertToggleClass("alertDlg alertDlgClosed"); within the setTimeout creates an infinite loop to showAlert(msg)-method.

As far as I can see, there is no recursivity is in setTimeout(...).

I can’t explain this behavior and would appreciate any helpful hints.

import './App.css';
import AlertDialog from './components/general/alert-dialog/AlertDialog';
import { Header } from './components/general/Header';
import MainView from './components/main/MainView';
import { useState } from "react";

function App() {
    const [alertMsg,setAlertMsg] = useState(""); 
    const [alertToggleClass,setAlertToggleClass] = useState("alertDlg alertDlgClosed"); 

    function showAlert(msg){
        console.log("Showing alert dialog");
        setAlertMsg(msg); // set message
        setAlertToggleClass("alertDlg"); // show alert dialog
        
        setTimeout(function() {
            if(alertToggleClass === "alertDlg" ){
                setAlertToggleClass("alertDlg alertDlgClosed");
                console.log("hide alert");
            }
            // setAlertToggleClass("alertDlg test");
        },3500);
    }
    return (
        <div className="container">
            <Header/>
            <MainView sendGlobalAlert={showAlert}/>
            <AlertDialog msg={alertMsg} toggleClass={alertToggleClass} />
        </div>
    );
}

export default App;

ReactJS Update child component after API call returns

So I have a simple reactJS app that contains a app.js with a HomePage.js

The HomePage.js need to display some data for me that I fetch trough an await API.get method from amplify. ( : https://docs.amplify.aws/lib/restapi/fetch/q/platform/js/ )
The API.get method triggers the .then response and then gives me exactly the correct array with item that I want.

Now I want to render those items on my HomePage.js, which is a functional component.

My app.js looks like this (ignore the token stuff, this is another problem i need to solve) :

import React, { useState } from "react";
import logo from './logo.svg';
import './App.css';
import Amplify, { API, Auth } from 'aws-amplify';
import { withAuthenticator , Link } from "@aws-amplify/ui-react";
import '@aws-amplify/ui-react/styles.css';
import { Button } from '@aws-amplify/ui-react';
import Appbar from "../src/components/Appbar/Appbar";
import Homepage from './components/Homepage/Homepage';

// let user;
let user = {}; 
let userName = "placeholder";
// let pageLoaded = false;
let passArray;
let zorgSearchData;

function App() {

  callApi();
  async function callApi() {
    user = await Auth.currentAuthenticatedUser()
    const token = user.signInUserSession.idToken.jwtToken
    userName = user.username;
    const requestData = {
      headers: {
        Authorization: token
      }
    }


    zorgSearchData = await API
    .get('caresyncapi' , '/items/zorgsearch/' + userName)
    .then(response => {
      console.log("resp!")
      console.log(response);
      passArray = response;
    })
  }

  return (
      <div className="App">
        <Appbar/>
        {<Homepage passedArray={passArray} />}

    </div>
    );  
  }


export default withAuthenticator(App);

The API.get calls and the .then prints out the exact response I want. I pass passArray as a prop to HomePage.js which (i think and am probably wrong) should update with the new data. The problem is when the .then is called there is no change in the Homepage.js . The props I retrieve in Homepage.js is always undefined. I think this is because the API is async and retrieves the prop after I pass it for the first time. But how do I update this? Anyway, my Homepage.js looks like this:

import React, { useState } from 'react';
import "./homepage.css";
import { makeStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import { Typography } from '@material-ui/core';

const useStyles = makeStyles((theme) => ({
    formControl: {
      margin: theme.spacing(1),
      minWidth: 120,
    },
    selectEmpty: {
      marginTop: theme.spacing(2),
    },
  }));

const Homepage = ({props}) =>{
    const classes = useStyles();
    const [age, setAge] = useState(''); 
    console.log(props);


    function handleChange (event) {
        console.log(event.target.value); 
        // console.log({passedData})
        //setAge(event.target.value);
    };

    return (
        <>
            <Typography variant="h1">{`Welcome,username`}</Typography>
                <FormControl variant="outlined" className={classes.formControl}>
                    <InputLabel id="demo-simple-select-outlined-label">Age</InputLabel>
                    <Select
                    labelId="demo-simple-select-outlined-label"
                    id="demo-simple-select-outlined"
                    value={age}
                    onChange={handleChange}
                    label="Patienten"
                    >
                        {/* {this.state.searchData.map(x=> <MenuItem >{x.PatientNaam}</MenuItem>)} */}
                        <MenuItem value="">
                            <em>None</em>
                        </MenuItem>
                        <MenuItem value={10}>Ten</MenuItem>
                        <MenuItem value={20}>Twenty</MenuItem>
                        <MenuItem value={30}>Thirty</MenuItem>
                    </Select>
                </FormControl>
            <div className="homepage-container">
                <div className="homepage-text-container">
                    <h1 className="welcome-message">Hello, {props}</h1>
                    <p>lorem ipsum</p>
                </div>
                <div className="chart-container">
                    <div className="chart-1">
                        <h3>Chart 1</h3>
                        <div className="chart"></div>
                        <p>More text....</p>
                        <p></p>
                    </div>
                </div>
            </div>
        </>
    )
}



export default Homepage

As you can see I am also trying to fill the select form with my array names, but I think I can figure that out as long as I have a valid array. I tried different methods of the handleChange and passing props, but nothing seems to work.

TL;DR : I have a app.js which calls an async get function, this returns a valid object I use. The problem is I pass this object array to Homepage.js ( {} ) before the async method returns a value. So the array is always undefined in Homepage.js

Can someone point me in the right way? Do I need to force a change? Is there a way to pass the prop again? Is there something I can do in the handleChange method? I can access the .then method, do I need to do something from there? Simply updating the variable doesn’t seem enough.

Thanks in advance! Sorry for the ramble im new to reactJS and I am trying to solve this problem after a few beers.

how to close the sidebar when clicking outside?

I’m a noobie at programing. I’m currently making a simple shop website for a project in class. I’m currently struggling with how to make it work.

This is my complete style sheet

     <style>
        .open{
            cursor: pointer;
            background-color: black;
            text-align: center;
            padding: 5px;
            font-size: 40px; 
        }
        
        .open i {
            color: white;
            height: 50px;
            width: 50px;
        }
        
        #Sidenav {
            height: 100%;
            width: 0px; 
            position: fixed;
            z-index: 1; 
            top: 0; 
            left: 0; 
            background-color: black;
            overflow-x: hidden; 
            transition: 0.5s; 
        }
        
        .logo {
            margin: 20px 0 0 0; /* top right down left */
            width: 75%;
            padding-bottom: 10px;
            border-bottom: 1px solid white;
        }
        
        .logo img {
            margin: 0;
            height: 100px;
            width: 100px;
            
        }
        
        .sidenav ul {
            margin: 0 0 0 12.5%;/* top right down left */
            padding: 0;
            width: 75%;
            list-style: none;
        }
          
        .sidenav ul li a {
            text-decoration: none;
            color: black;
            position: relative;
        }
        
        .sidenav ul li{
            margin: 10px 0 10px 0; /* top right down left */
            background-color: white;
            border-radius: 20px;
            text-align: center;
            line-height: 30px;
            font-size: 20px;
        }
    </style>

All of HTML codes are working fine

<body>
    <span class="open" onclick="OpenNav()"><i class="fas fa-bars"></i></span>/* My button */

    <nav id="Sidenav" class="sidenav">
            
            <center>
                <div class="logo">   
                    <<img src="#" alt="logo"/>
                <div>
            </center>
            
            <ul>
                <li><a href="#">All Items</a></li>
                <li><a href="#">Smartphones</a></li>
                <li><a href="#">Appliances</a></li>
                <li><a href="#">PC Components</a></li>
                <li><a href="#">Software</a></li>
                
                <li><a href="#">My Cart</a></li>
                <li><a href="#">Account</a></li>
                <li><a href="#">Shop Inventory</a></li>
                <li><a href="#">Login</a></li>
            </ul>
        </nav>
    
    <h1>Content
    <div id="main">
        
    </div>

The function OpenNav() work fine as well, but when I put the Closenav function I can’t click on anything else.

    <script>
        function OpenNav() {
          document.getElementById("Sidenav").style.width = "250px";
        }

        document.onclick = function(Closenav){
           if(Closenav.target.id !== 'Sidenav'){
              document.getElementById("Sidenav").style.width = "0px";
           };
        };
    </script>
</body>

Why quick sort is always slower than bubble sort in my case?

They use same array:

QUICK SORT Time: 3159 miliseconds (array length 10K)

Bubble SORT Time: 1373 miliseconds (array length 10K)

I’m trying to compare time of the sorting using quick and bubble sort algoritms. I use the array with 10K different random numbers sorted in random order for both functions. But for some reason bubble sort is always sort array faster than quick sort, even if average time complexity of bubble sort is worse than average time complexity of quick sort. Why bubble sort algorithms slower than quick sort algorithm in my case? (I tried different lengths of array, from 10 to 10K)

Thats my quick sort function

let quickSort = (arr) => {
    if (arr.length <= 1) {
        return arr
    }
    const pivot = arr[0]
    const rest = arr.slice(1);
    let left = [],
        right = [];
    rest.forEach(el => el > pivot ? right = [...right, el] : left = [...left, el]);
    return [...quickSort(left), pivot, ...quickSort(right)];
}

And that’s my bubble sort function

let bubbleSort = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        for (let s = i + 1; s < arr.length; s++) {
            if (arr[s] < arr[i]) {
                let a = arr[i];
                arr[i] = arr[s]
                arr[s] = a;
            }       
        }
    }
    return arr
}