How can I pass values between parent page js and child popup js?

My parent page js file script:

var PopupConnect = window.open("http://localhost:8080");
var popup_function = PopupConnect.CreateText();

My popup page js file script:

function CreateText() {
  var text = "random text";
  return json({
        result: text
      })
}

This js line in parent page runs fine which triggers a new tab in the browser:

PopupConnect = window.open

The error I am getting is in the line after it:

Uncaught TypeError: PopupConnect.CreateText is not a function

How can I call the js function in child page from the parent page js correctly? Is that even possible? And how can I pass back the result from CreateText function to the parent page js?

NOTE: The parent page is running on Python server & the child popup page is running on Node.js server. Both pages of course are opened in the same browser.

Some people might suggest using localStorage.setItem and localStorage.getItem method but it doesn’t work the two pages are running on different localhost ports and of course in production they will be running on different domains. FYI I have already tried this method and it didn’t work.

Twitter API v2 Search Tweets: 401 Error when fetching in Next.js, yet successful when -curl using same Bearer Token?

I am using the Search Tweets API from Twitter. I am receiving a 401 error “Unauthorized”. I have verified that the bearer token works, when I -curl the same request I do get a successful response. I have also tried replacing the .env variable with the bearer token string and receive the same error. Am I doing something wrong when fetching in a Next.js/React component?

const testQuery = 'animals'

useEffect(() => {
  const fetchLatestTweets = async () => {
    try {
      const response = await fetch(
        `https://api.twitter.com/2/tweets/search/recent?query=${testQuery}`,
        {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${process.env.twitterBearerToken as string}`,
            'Content-Type': 'application/json'
          },
          mode: 'no-cors'
        }
      )
      console.log('res', await response.json())
      setTweets(await response.json())
    } catch (err) {
      console.error(err)
    }
  }
  fetchLatestTweets()
}, [])

how to interpret content-length for XHR requests?

I want to track progress for uploading a large file which I’m chunking on the client using XHR.
On my server, I take some data out of the form and persist N bytes to disk. What I’m confused about is that if I don’t return the exact value that the client sent, it gets a content-length mismatch error. How does this make sense?

I send a form, with say 100 bytes and 80 of the bytes are the data I write to disk. Once I write the 80 bytes to disk, the server returns 80 for the content-length header. Why does the browser assume that I should write the same amount of bytes I sent?

Getting a warning in console “You are calling ReactDOMClient.createRoot() on a container that has already been passed to createRoot() before.”.”

I am trying to implement a Redux in a simple React application that uses the latest version (React 18). Here is my code in index.js so far:

import React from 'react';
import ReactDOM from 'react-dom/client';
import { store, App } from './App';
import { createStore } from 'redux'

export const renderApp = () => {
    ReactDOM.createRoot(document.getElementById('root')).render(<App />);
}

renderApp()

store.subscribe(renderApp)

However, I get a warning in the console that says:

“You are calling ReactDOMClient.createRoot() on a container that has
already been passed to createRoot() before. Instead, call
root.render() on the existing root instead if you want to update it”

What is the supposed to mean, and how would I need to change my code in index.js?

Javascript OCR tesseract.js recognize and copy number after spaces

i want to use tesseract.js libaray to recognize a string like (“رقم العداد”) and alert the number that is written after the string like (7038842 رقم العداد) << as you see i want to alert the number after the string from a png picture and copy another number from the picture (“نقطة الخدمة”) this is what i have tried and it works fine if the [ text.match ] string was [القراءة] but if i change it to (“رقم العداد”) or (“نقطة الخدمة”) no alert pops up and gives me this error on console

Uncaught (in promise) TypeError: Cannot read properties of null (reading ‘1’)
at (index):25:63

code :-

Tesseract.recognize(
        'Uff.png',
        'ara',
  { logger: m => console.log(m) }
).then(({ data: { text } }) => {
    
    var number = 'رقم العداد'; or /*'نقطة الخدمة'*/
    var result = text.match(new RegExp(number + '\s+(\w+)'))[1];
    alert(result);
})
    </script>

picture or image link :-
picture

Mathematical Function Returning NaN Error (JavaScript)

I am trying to fix a NaN error.

When running the code on the console it gives me the correct answer. However, when I try to print it on a HTML H1 tag the code returns a NaN error.

I tried to use native functions (ie.: parseFloat(), .toString();), but it didn’t work as planned.

Could you shed a light, please?

const tempConvert = parseFloat (document.querySelector('input'));

function convertTemp(tempConvert) {
    switch (slt.value) {
        case 'farenheit':
            document.querySelector('h1').innerHTML = `${convertCToF(tempConvert)} Fº`;
            break;
        case 'kelvin':
            document.querySelector('h1').innerHTML = `${convertCToK(tempConvert)} Kº`;
            break;
        default:
            alert('Selec an option.');
            break;
    }
}


function convertCToF(tempC) {
    return tempC * 1.8 + 32;
}

function convertCToK(tempC) {
    return tempC + 273.15;
}

How do I add hover effects over buttons on Vue.js 3?

I am building a calculator to help practice learning Vue.js 3 (I am new to vue). I have got the basic functionalities down but I am trying to figure out how to add a hover animation over the buttons. If possible I am trying to make a different hover color between the buttons in white and buttons in orange. Any help would be appreciated!
[enter image description here][1]
Code:

  <div class="calculator">
  <div class="display">{{ current || '0'}}</div>
  <div @click="clear" class="btn">C</div>
  <div @click="sign" class="btn">+/-</div>
  <div @click="percent" class="btn">%</div>
  <div @click="divide" class="operator">÷</div>
  <div @click="append('7')" class="btn">7</div>
  <div @click="append('8')" class="btn">8</div>
  <div @click="append('9')" class="btn">9</div>
  <div @click="multiply" class="operator">x</div>
  <div @click="append('4')" class="btn">4</div>
  <div @click="append('5')" class="btn">5</div>
  <div @click="append('6')" class="btn">6</div>
  <div @click="minus" class="operator">-</div>
  <div @click="append('1')" class="btn">1</div>
  <div @click="append('2')" class="btn">2</div>
  <div @click="append('3')" class="btn">3</div>
  <div @click="plus" class="operator">+</div>
  <div @click="append('0')" class="zero">0</div>
  <div @click="dot" class="btn">.</div>
  <div @click="equal" class="operator">=</div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      previous: null,
      current: '',
      operator: null,
      operatorClicked: false,
      hover: false
    }
  },

  methods: {
    clear() {
      this.current = '';
    },

    sign() {
      this.current = this.current.charAt(0) === '-' ?
      this.current.slice(1) : `-${this.current}`;
    },

    percent() {
      this.current = `${parseFloat(this.current) / 100}`;
    },

    append(number) {
      if (this.operatorClicked) {
        this.current = '';
        this.operatorClicked = false;
      }
      this.current = `${this.current}${number}`;
    },

    dot() {
      if (this.current.indexOf('.') === -1) {
      this.append('.')
      }
    },

    setPrevious() {
      this.previous = this.current;
      this.operatorClicked = true;
    },

    plus() {
      this.operator = (a,b) => a + b;
      this.setPrevious();
    },

     minus() {
      this.operator = (a,b) => a - b;
      this.setPrevious();
    },

     multiply() {
      this.operator = (a,b) => a * b;
      this.setPrevious();
    },

     divide() {
      this.operator = (a,b) => a / b;
      this.setPrevious();
    },

     equal() {
      this.current = `${this.operator(
      parseFloat(this.current),
      parseFloat(this.previous)
      )}`;  
      this.previous = null;
    }
  }
}
</script>

<style scoped>
.calculator {
  margin: 0 auto;
  width: 400px;
  font-size: 40px;
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-auto-rows: minmax(50px, auto);
}

.display {
  grid-column: 1 / 5;
  background-color: black;
  color: white;
}

.zero {
  grid-column: 1 / 3;
  border: 1px solid black;
}

.btn {
  background-color: white;
  border: 1px solid black;
}

.operator {
  background-color: orange;
  color: white;
  border: 1px solid black;
}
</style>```


  [1]: https://i.stack.imgur.com/woC73.jpg

Create any asyncronous function in Javascript

The object of this question is better understanding of the javascript event loop.

So I was thinking about how could I execute any blocking code asyncronously in JS.

for exemple, a cpu bound problem like:

let i = 0;
while(i < 1_000_000_000) i++

So this CPU bound being asyncronous is the same as JS working this out concurrently.

My first though was : “lets use setTimeout and Promises (just like someone would do in Node.js I guess )

const blockingAsync = () =>{
    return new Promise((resolve, reject) => {

        setTimeout(()=>{
                let i = 0;
        while(i < 2_000_000_000)i++
        console.log(i)
        }, 0 )
        resolve(i)
    })
}

then if I do something like

console.log('first');
blockingAsync().then(r => console.log(r));
console.log('second');

the output is successfully:

first
second
1_000_000_000

But it does hold the event loop
If I try to add:

console.log('first');
blockingAsync().then(r => console.log(r));
setTimeout(()=>console.log('should print first'), 0)
console.log('second');

The output is :

first
second
1_000_000_000
should print first

And I supposed that happens because blockingAsyncwhen is called it blocks the cpu until is finished and poped from the execution stack. And then the next callback to be called is the latter added setTimeout.

setTimeout could be a busy waiting for a few ms. So it could be blocking, but it isn’t.

I’ve checked out this https://stackoverflow.com/a/50501467/14364268 setTimeout implementation “from scratch” to think how could be implemented using the callback stack and event queue on js.

So my first question is: what would be necessary to make a cpu-bound non-blocking? Just like setTimeout probably behaves?

Context: This is an exercise to understand event-loop. I want to understand how can I create asyncronous events myself.

how do i make wishlist in react js

I’m making wish list in react js.

I want that when i clicked wish button about something goods, the goods is added on wish list by boolean data “liked: true”.

And i want that if i click one more when boolean data true, the goods is delete on wish list by boolean data “liked: false”

But now, when i clicked wish button, the liked data changed to true, but not added on wish list.

And, i clicked one more, but it didn’t changed to false.

How can i fix my code?

This is my code.

import { useParams } from "react-router-dom";
import axios from "axios";
import { useEffect, useState } from "react";
import "./goods.css";

const Goods  = (props) => {
  const [boards, setBoards] = useState({});
  const [images, setImages] = useState([]);
  const {id}  = useParams();
  const [isWishAdd, setIsWishAdd] = useState(false);
  const [wishCount, setWishCount] = useState(0); 

  const wishAddHandler = () => {
    setIsWishAdd(!isWishAdd);
  }

  const wishCountHandler = () => {
    wishAddHandler()
    if (!isWishAdd) {
      setWishCount(wishCount +1)
      fetch(`https://27.96.131.85:8443/api/likeBoards/${boards.id}`, {
        credentials: 'include',
        method: "POST",
        body: JSON.stringify({
         "liked": true
        }),
      })
      alert("찜 목록에 추가되었습니다.")
      console.log(boards)
      console.log("count+1")
    } else if (isWishAdd) {
      setWishCount(wishCount -1)
      fetch(`https://27.96.131.85:8443/api/likeBoards/${boards.id}`, {
        credentials: 'include',
        method: "DELETE",
        body: JSON.stringify({
          "liked": false
        })
      })
      alert("찜 목록에서 삭제되었습니다.")
      console.log(boards)
      console.log("count-1")
    }
  }    
  

  useEffect(() => {
    (async function () {
      const response = await axios.get(`https://27.96.131.85:8443/api/boards/${id}`, {
        withCredentials: true,
      });
      const boards = response.data;
      const images = boards.boardImages;
      console.log(response.data);

      // 게시글 정보 state에 저장
      setBoards(boards);
      setImages(images);

    })();
  }, []);

    return(
      <div id="goods">
        <p className="goodsTitle">상품 정보</p>
        <div className="images_container">
          {
            images.map((images) => {
              return (
                <img className="goodsImages"
                src={`https://27.96.131.85:8443/api/images/${images.id}`} />
              )
            })
          }
        </div>
       
        <div className="goodsContext">  
          <div className="goodsBoardTitle">
            {boards.title}
          </div>
          
          <div className="goodsName">
            상품 : {boards.goodsName}
          </div>

          <div className="goodsPrice">
            가격 : {boards.price} 원
          </div>

          <div className="goodsWriter">
            판매자 : {boards.writer}
          </div>
          
          <div className="goodsText">
          {boards.content}
          </div>

          <div className="goodsBtn">
            <span className="zzimBtn">
              <button class="btn btn-primary" type="submit" onClick={wishCountHandler}>찜 하기</button>
            </span>
            <button class="btn btn-primary" type="submit">판매자와 대화</button>
          </div>
        </div>
      </div>
    );
};

export default Goods;

This is api server

enter image description here

and this is my object data structure
enter image description here

laravel ajax response.status undefined in console

when i am making validation in the form i made it with ajax
but in ajax when i wrote this console.log(response) it works but when i wrote like this
console.log(response.status) it returns undefined i don’t know why although i wrote status at response->json() and also the same when i make console.log(response.errors)

and here is my code

my form blade

 <form method="POST" enctype="multipart/form-data" id="productform">
        @csrf
        @method('POST')
        <ul id="showerrors">

        </ul>
        <div class="form-group">
            <label for="">name</label>
            <input type="text" name="name" class="form-control">
        </div>
        <div class="form-group">
            {{-- <label for="">image</label>
            <input type="file" name="image" class="form-control"> --}}
        </div>
        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
        <button type="submit" class="btn btn-primary">Save changes</button>
</form>

and myy response code in store method

public function store(Request $request)
{
    $validation = Validator::make($request->all(),[
        'name' => 'required',
    ]);


    if($validation->fails()){
        return response()->json([
            'errors' => $validation->errors(),
            'status' => 400,
        ]);
    }
    // dd($request->all());

        $product = new Product();
        $product->name = $request->name;
        $product->save();

    return response()->json([
        'status' => 200,
        'message' => 'added successfully',
    ]);
}

and my route

Route::resource('products',AppHttpControllersProductController::class);

and my ajax code that returns console.log(response.status) undefined

$(document).ready(function(){
    

    $('#productform').submit(function(e){
    e.preventDefault();
    var data = {
        'name' : $("input[name='name']").val(),
        '_token' : $("input[name='token']").val(),
    }
    // console.log(data);
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
        $.ajax({ 
            url:"/products",
            type : "POST",
            data:data,
            dataType:'text',
            success:function(response){
                console.log(response.status);
                if(response.status = 400){
                    $('ul#showerrors').html = "";
                    $('ul#showerrors').addClass = "alert alert-danger";
                    $.each(response.errors, function (key,value){
                        $('ul#showerrors').append('<li>'+value+'</li>');
                    });
                }
            },
        });
    });
});

Vue.JS – Api request – Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘quote’)

<template>

    <article class="message is-warning">
        <div class="message-header">
            <span>Code Quotes</span>
        </div>
        <div class="message-body">
                <span v-html="fetchedQuotes.data.quote"></span>
                <span>{{fetchedQuotes.data.author}}</span> 
        </div>
    </article>

</template>

<script>
    export default {
        data(){
            return {
               
                fetchedQuotes: [],
                contentUrl: "https://apiurl.tld/"
            };
        },
        mounted() {
            this.getQuotes(this.contentUrl, "quotes");
            
        },
        methods: {
            async getQuotes(url, collection) {
                try {
                    
                    let response = await fetch(url + collection+"/"+Math.ceil(Math.random()*6));
                    this.fetchedQuotes = await response.json();
                } catch (error) {
                    console.log(error);
                }
            }
        }
    };
</script>

I am trying to randomly fetch quotes from a Directus project API.
But this code keeps giving me the error: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading ‘quote’).

I have tried several different solutions but now I am stuck and need help figuring out whats preventing this code from working.

Any help will be appreciated.

Regards,
TG

React img onError not firing

I am trying to use a third-party API for getting YouTube thumbnails with higher resolution, which sometimes fails with code 404. If I fail to fetch the image, I would like to replace the src with the default YouTube thumbnail retrieved using its own API (I have the url stored in a json). When I tried to implement this using the img onError event, it appears that nothing is fired when the fetch fails. Does anybody know what’s going on? Thanks!

const TestView = () => {

    const videoId = "1KUZHKI-BDk"

    return (
        <div>
            <img src={`https://img.youtube.com/vi/${videoId}/maxresdefault.jpg`} onError={() => {console.log("errored")}}></img>
        </div>
    )
}

How to find time from timezone standard name using moment

I have the time zone info as shown in below JSON.

{"timezone_standard_name": "(UTC-06:00) Central Time (US & Canada)"}.

Is it possible to find the date and time for the above time zone.

I have already tried to find UTC time then add the offset but it will just give me the date and time object in IST

Before offset

enter image description here

After adding offset

enter image description here

This is what I have tried. Do we have any better answer?
Find the offset that is +360 using string manipulation (UTC-06:00)

const tzNames = momenttz.tz.names();
const map = new Map();

for (const name of tzNames) {
  const offsets = momenttz.tz.zone(name).offsets;
  for (const offset of offsets) {
    if (!map.has(offset)) {
        map.set(offset, new Set());
    }
    map.get(offset).add(name);
  }
}
const offsetList = map.get(360);
for (const item of offsetList) {
  console.log(item);
  let tx = momenttz().tz(item).format();
  console.log('Time in given zone is = ' + tx);
}

Says that username/password entered is empty even though it isn’t

I am making an app and right now I am coding the backend with express js in node js. For some reason, It is saying that the username and password is invalid.

Backend testing

app.get("/signUp", async (req, res) => {
const json = req.body;
const user = await UserModel.findOne(json["username"])
if(!json["username"] || json["username"] === "" || !json["password"] || json["password"] === "") {
    return res.status(400).send({
        "status": 400,
        "message": "Username and/or password is empty. New user was not created"
    })
}
else if(user.type != null) {
    return res.status(409).send({
        "status": 409,
        "message": "User already exists with given username. New user was not created."
    })
}
else {
    await UserModel.create({
        username: json["username"],
        password: json["password"] 
    })
    return res.status(200).send({
        "status": 200,
        "message": "New user was created."
    })
}

})