How to solve “Unhandled Rejection (TypeError): Failed to fetch” problem in ReactJS?

I want to fetch data from an HTTP request(Witch I created in Spring Boot), but I am getting this error:

Unhandled Rejection (TypeError): Failed to fetch

This is my code:

const getData=()=>{
    fetch('http://localhost:8080/data'
    ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    }
    )
      .then(function(response){
        console.log(response)
        return response.json();
      });
  }
  useEffect(()=>{
    getData()
  },[])                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   

}

solve ERR_OSSL_EVP_UNSUPPORTED in npm run serve

I get this error when I run “npm run serve”:

opensslErrorStack: [ ‘error:03000086:digital envelope routines::initialization error’ ], library: ‘digital envelope routines’,
reason: ‘unsupported’,
code: ‘ERR_OSSL_EVP_UNSUPPORTED’

I updated the npm but still have the same error.
can anyone help me?

React Link async/await does not wait code block

Hey I am trying to make small application for React-router I am trying to send API request (I do not have backend thats why im using promises) When i click Link it is redirecting not waiting my async/await could you tell me what am i doing wrong?
First thought i can pass history with props and then

history.push("/someURL");

But my second thought is if i could do this with <Link I will pass less props (history).

To sum up i need to wait until my request(promise) over after that i need to change url

import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import { Link } from 'react-router-dom';
import { toast } from 'react-toastify';

const StyledButton = styled.button`
  width: 100%;
  border-radius: 10px;
  background-color: #24b571;
  color: #ffffff;
  font-weight: bold;
  margin-bottom: 5px;
`;

const SaveButton = ({
  children,
  saveValidation,
  message,
  to,
  setIsLoading,
}) => {
  const promiseFunc = () =>
    new Promise((resolve) => {
      setTimeout(() => {
        resolve(5);
      }, 5000);
    });

  const onClickHandler = async (event) => {
    setIsLoading(true);
    const control = saveValidation(); // returns true or false
    if (!control) {
      toast.error(message);
      event.preventDefault();
    } else {
      try {
        const a = await promiseFunc();
        alert(a);
      } catch {
        alert('error');
      }
      console.log(control);
    }
    setIsLoading(false);
  };

  return (
    <Link to={to}>
      <StyledButton onClick={onClickHandler}>{children}</StyledButton>
    </Link>
  );
};

export default SaveButton;

SaveButton.propTypes = {
  children: PropTypes.node.isRequired,
  saveValidation: PropTypes.func.isRequired,
  to: PropTypes.string.isRequired,
  message: PropTypes.string,
  setIsLoading: PropTypes.func,
};
SaveButton.defaultProps = {
  message: 'Fill all values',
  setIsLoading: () => {},
};

Adding html mouseover function with javascript

I’m trying to write an html MUD game with javascript.
I try to print a message that shows a picture of the character performing the action when moused over.

Here is my code so far

function printMessage(message,char){

$("#messageScreen").append('<p onmouseover="showPicBottom('+char.race+','+char.pic+')" onmouseout="removePic()">'+""+message+"</p>");

}

function showPicBottom(race,pic){
    var pichtml="";
    if (origin=="Human"){
        pichtml='<img src="img/human/'+"Pic ("+pic+")"+'.PNG"/ width="200">';
    }else{
        pichtml='<img src="img/elf/'+"Pic ("+pic+")"+'.PNG"/ width="200">';
    }
    $("#picBottom").append(pichtml);
}

I always get “Uncaught SyntaxError: Unexpected token ‘,'”. I think it’s the quotation marks but I haven’t found a way. How do I fix it?

Get google translate language plain javascript on select from dropdown

I want to get the selected language from an embedded Google translate script in a dynamic php website.

I have inserted in the head

<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'el', includedLanguages: "en,el" 
 }, 'google_translate_element');
 }
 </script>
 <script type="text/javascript" src="//translate.google.com/translate_a/element.js? 
 cb=googleTranslateElementInit"></script>

and in body:

<div style="text-align:center!important;" id="google_translate_element"></div>

and translate dropdown appears ok and does the job ok.

I want to detect the selection of the language, so I run some script depending on the selection.

So far the javascript that is executing correctly is:

<script type="text/javascript">
window.setInterval(function(){
 lang = $("select.goog-te-combo option:selected").text();
alert(lang);
 },7000);
 </script>

that shows an alert window every 7 sec with the selected language text.

How do I change the above script so that is executed only on dropdown selection change?

Google Apps Script: Uncaught console error

I’m trying to debug a Console error I’m getting for one particular user.

This is the error message we are getting
enter image description here
enter image description here

The code:

    function createCopies(){
      //loading
      if(validateForm()){
        console.log("form validated")
        loadingStart();
        var copies_obj = {};
        copies_obj.number = document.getElementById("copies_number").value == "" ? 1 : document.getElementById("copies_number").value;
        console.log("copies # " + copies_obj.number)

        google.script.run.withSuccessHandler(function(res){
          document.getElementById("save-success-message").classList.remove("invisible");        
          setTimeout(function(){
            document.getElementById("save-success-message").classList.add("invisible");
          }, 4000);
          //done loading
          loadingEnd();
        }).replicateTemplate(copies_obj);
      }else{
        $('#errorNotification').toast('show');
      }
    }

Function that is being called

function replicateTemplate(copies_obj) {
  //JE Copies Reference Sheet. Put the information on the first Sheet found.
  //If we add sheets to this Spreadsheet lets add them to the right side.
  var template_list_sheets = SpreadsheetApp.openById(template_list).getSheets();
  var template_list_sheet_0 = template_list_sheets[0];

  //Start looping to create the X number of copies
  Logger.log("copies #: " + copies_obj.number)
  for(var i = 0; i < copies_obj.number; i++){
    var template_date = Utilities.formatDate(new Date(), SpreadsheetApp.getActive().getSpreadsheetTimeZone(), "MM/dd/yyyy hh:mm:ss")
    var template_list_rows = template_list_sheet_0.getLastRow();
    var fe_destination_folder = DriveApp.getFolderById(fe_folder);
    var be_destination_folder = DriveApp.getFolderById(be_folder);

    //1. Make a copy of the original template; save the original name & get the newly create template id
    var original_fe_template = DriveApp.getFileById(fe_template);
    var fe_template_name = original_fe_template.getName(); 
    var new_fe_template = original_fe_template.makeCopy().getId();

    //2. Grab the newly created template, get its url and rename the file
    var new_fe_file = DriveApp.getFileById(new_fe_template);
    var new_fe_url = new_fe_file.getUrl();
    new_fe_file.setName(fe_template_name.replace("###",template_list_rows));
    
    //3. Repeat for BE Template
    var original_be_template = DriveApp.getFileById(be_template);
    var be_template_name = original_be_template.getName();
    var new_be_template = original_be_template.makeCopy().getId();
    
    var new_be_file = DriveApp.getFileById(new_be_template)
    var new_be_url = new_be_file.getUrl();
    new_be_file.setName(be_template_name.replace("###",template_list_rows));

    //4. Update the Named Ranges
    SpreadsheetApp.openById(new_fe_template).getRangeByName("BELink").setValue(new_be_url);
    SpreadsheetApp.openById(new_be_template).getRangeByName("FELink").setValue(new_fe_url);
    SpreadsheetApp.openById(new_be_template).getRangeByName("CopyNumber").setValue(template_list_rows);

    //5. Once the files are done, move them to the destination folder
    DriveApp.getFileById(new_fe_template).moveTo(fe_destination_folder);
    DriveApp.getFileById(new_be_template).moveTo(be_destination_folder);

    //6. Add the files URL into the Reference Sheet
    var new_row = [template_list_rows, template_date, new_fe_url, new_be_url];
    template_list_sheets[0].appendRow(new_row);

  }
}

At this point I’m not really sure where to dig in order to diagnose what is wrong.
We have tested the same script with other users without any issue, but the error message doesn’t give us any clear clue.

Note: The user has access to all the files used during the script execution

click event listener method is not working on a specific div

I am trying to add an event listener to my “degree section div” but it is not working nor am I getting any errors. I have tried multiple ways of traversing the DOM to reach the “degree-section” div but to no avail.

Any kind of help is welcome and appreciated

The HTML:

<body>

    <div class="loc-container">
        <div class="location">
            <h1 class="city-name">City</h1>
            <div class="weather-icon"><img src="icons/unknown.png" /></div>
       </div>
    </div>
   
    

    <div class="weather-info">

        <div class="degree-section">
            <h2 class="temp">0.0</h2>
            <span>K</span>
        </div>

        <div class="check">
            <label for="celcius">Convert</label>
            <input type="checkbox", name="celcius", id="celcius">
        </div>
    

        <div class="info-section">
            <div class="info-flex">
                <h3 class="feels-like">0K</h3>
                <h4>Feels Like</h4>
            </div>

            <div class="info-flex">
                <h3 class="humidity">0</h3>
                <h4>Humidity</h4>
            </div>

            <div class="info-flex">
                <h3 class="wind">0</h3>
                <h4>Wind</h4>
            </div>
        </div>  
    </div>
    

    <div class="top-center">
        <div class="form">
            <input type="text" name="city" id="city" required>
            <label for="city" class="label-name"><span class="search-name">Search City...</span></label>
            
        </div>
        <!-- <i class="fas fa-search search-btn"></i> -->
        <i class="material-icons search-btn" style="font-size: 35px;">search</i>
    </div>

    
    <script src="weather.js"></script>
</body>

Here is my javascript:

let city = document.querySelector('#city');
let searchbtn = document.querySelector('.search-btn');
let city_name = document.querySelector('.city-name');
let temp = document.querySelector('.temp');
let feels_like = document.querySelector('.feels-like');
let humidity = document.querySelector('.humidity');
let locationIcon = document.querySelector('.weather-icon');
let checkbox = document.getElementById('celcius');
let weather_sec = document.querySelector('.weather-info');
let degree_section = weather_sec.firstElementChild;
let degree_section_span = degree_section.getElementsByTagName('span')[0];


//let wind = document.querySelector('.wind');



async function getUrl(city){

    try{
        let theUrl = url + city + '&appid=' + apiKey;
        let response = await fetch(theUrl , {mode: 'cors'})
        let data = await response.json();
        //Get data from api and change html content based on the recieved data
        let temp_data = data.main.temp
        temp.textContent = temp_data;
        let feels_like_data = data.main.feels_like;
        feels_like.textContent = feels_like_data + "K";
        let humidity_data = data.main.humidity;
        humidity.textContent = humidity_data;
        let {icon} = data.weather[0];
        locationIcon.innerHTML = `<img src="icons/${icon}.png">`;

         //change K to C
         degree_section.addEventListener('click', ()=>{
             //logging a message just to check if it is working
            console.log("c")
        })
         
        

    }catch(err){
        let error = document.createElement('span')
        error.className = "error";
        error.textContent = "Location does not exist"
        let top_center_div = document.querySelector('.top-center')
        top_center_div.appendChild(error)
        city_name.textContent = "No city found"
    }  
}






searchbtn.addEventListener('click', (e)=>{
    let cityName = city.value;
    city_name.textContent = cityName
    console.log(cityName)
    getUrl(cityName)
})

Thank you in advance!

how do i check the textcontent inside a button. the if statement isnt recognising the text

Linkedin search result
so on the search page i want to only select the buttons with connect on them. the if statement doesnt seem to check if connect is the text content.

 var buttons = document.getElementsByClassName(
'artdeco-button artdeco-button--2 artdeco-button--secondary ember-view'


)

  for (var i = 0; i < buttons.length; i++) {
    console.log(buttons[i].textContent)
    if (buttons[i].textContent == 'Connect') {
      console.log(i)
    }
    
  }

result
Shouldnt the connect have an corresponding i?

Cannot create pdf of current electron browser. Have problem with method printToPDF

With the code snippets below, I am trying to create a pdf file showing the contents of the electron browser.

I am seeing first three console logs, but cannot see the one right after the printToPDF method.
Looks like it got stuck reaching printToPDF method and I have no error messages to share.
Any idea why cannot go further ?

Main.js:

"use strict";
const electron = require('electron')
const fs = require('fs')
const app = electron.app
const BrowserWindow = electron.BrowserWindow
const ipc = electron.ipcMain
const path = require('path')
const url = require('url')
const shell = electron.shell

ipc.on("print-to-pdf", function (event) {
console.log("reached to ipc");
const pdfPath = "C:\Temp\print.pdf";
console.log("pdfPath:" + pdfPath);
const win = BrowserWindow.fromWebContents(event.sender);
console.log("created const win");
win.webContents.printToPDF({printBackground: true, landscape: true},function (error, data) {
    console.log("reached to printToPDF method:");
    if (error) throw error;
    fs.writeFile(pdfPath, data, function (error) {
    if (error) {
        throw error;
    }
    shell.openExternal("file://" + pdfPath);
    event.sender.send("wrote-pdf", pdfPath);
    });
});
});

Object key based on array values

I have array: const arr = ['foo', 'bar', 'bax'];

I want to create an object based on array entries:

const obj = {
  foo: true,
  bar: true,
  bax: false,
  fax: true, // typescript should show error here because "fax" is not in "arr"
};

How to tell typescript that all keys of obj must be inside arr?

Converting an array of data to JSON using a property map

I am trying to convert a 2d array into a json object using a key map.
The key map looks like

var keys = ['id', 'title', 'customer.id', 'customer.name', 'customer.phone.home', 'customer.phone.mobile' ];

and the data is

var data = [
  [1, 'Task 1', 'C1', 'Customer 1', '999', '8888'],
  [2, 'Task 2', 'C2', 'Customer 2', '333', '5555']
];

Output JSON should be

    var output = [
   {
      "id":1,
      "title":"Task 1",
      "customer":{
         "id":"C1",
         "name":"Customer 1",
         "phone":{
            "home":"999",
            "mobile":"8888"
         }
      }
   },
   {
      "id":2,
      "title":"Task 2",
      "customer":{
         "id":"C2",
         "name":"Customer 2",
         "phone":{
            "home":"333",
            "mobile":"5555"
         }
      }
   }
];

I am trying to do it something like but I am not good here making smerecursion etc. Could anyone help please?

function arrToJSON(headers, data){
  var output = [];
  data.forEach(row, index){
    var cObj = {};
    headers.forEach(header, itemIndex){
      var headerParts = header.split('.');
      // NOt sure what to do here
    }
  }
}

function callback give an error while using inside onload event

I am trying to return value within onload function via callback but console give me Uncaught TypeError: callback is not a function

async function base64SquareCrop(imgbase64, size = 224, callback) {
const img = document.createElement("img");
await img.setAttribute("src", imgbase64);

let width = 1240;
let height = 698;
const min = Math.min(width, height);
const scale = size / min;
const scaledW = Math.ceil(width * scale);
const scaledH = Math.ceil(height * scale);
const dx = scaledW - size;
const dy = scaledH - size;
canvasImage.width = canvasImage.height = size;
const ctx_img = canvasImage.getContext("2d");
img.onload = function() { ctx_img.drawImage(
    img,
    ~~(dx / 2) * -1,
    ~~(dy / 2) * -1,
    scaledW,
    scaledH
);
var sss = canvasImage.toDataURL("image/png");
callback(sss);
} 

Send IPC message from main process to renderer process Electron

Currently I have an Electron menu with a save button on it. When this save button is pressed I wish to send an event to the renderer process, for the renderer to handle the event.

Here is what I have attempted:

Menu Source

const menuTemplate = [
    {
        label: "File",
        submenu: [
            {
                label: "Save",
                accelerator: "Ctrl+S",
                click: () => {
                    BrowserWindow.getFocusedWindow().webContents.send("save");
                }
            },
        ]
    },
]

Renderer Source

ipc.on("save", () => {
    console.log("save");
})

When trying this I get no output whatsoever when pressing the save button, including no errors. I can confirm that the correct menu is being utilised by Electron and that the click() function is executing. I can also confirm that ipc.on is indeed defined in the renderer.

How can I get this working? Thanks in advance.

require from exported file in node script

Trying to require .ts file that uses the export syntax in .js node script and getting the following error:

export {
^^^^^^

SyntaxError: Unexpected token 'export'

How can I do it succesfully? I can’t use babel or change anything in package.json. Any ideas?