How is fetch call working from command line when I specified an origin in my node js app

I have the following settings in my node js (I’m using Express) app:

app.use(cors({ origin: 'http://localhost:5001',credentials: true }))

I am having cors issues with my React frontend (different story!). However, I wrote a simple JS script using fetch:

import fetch from 'node-fetch'       
 var response = await fetch('http://remote_server.com', {
      method: 'GET',
      headers: {
        'Content-type': 'application/json'
      }
    })

var data = await response.json()
console.log(data)

The above code works when run from my VSCode Terminal (localhost is NOT running)!? Why is it working even though I specified the origin in my backend code?

Javascript Open file selector with a particular folder and files selected

From browser using javascript (any framework) is it possible to open the file select dialog with a particular folder and files within that folder selected.

I have an angular application where user is allowed to upload as many number of files from any folder. Now after user chooses the set of files and clicks the open button we start uploading the files 1 by 1 into s3 , Now in case any upload fails we want to exit the process and allow user to resume upload from where it failed.

Since from browser we cannot access system files to upload , the only way left out is when user clicks the resume button to automatically open the file select dialog for the user with the pending files selected.

We are not finding a way to do that. Any help regarding that will be highly appreciated.

Regex for urls and markdown like images

I’m having trouble making two regex for a url parser in JavaScript. Let me explain.

I have two different regex, one to parse images with a markdown syntax, and one to parse plain urls.

So, if I have ![Alt Text](https://stackoverflow.com/) it should parse to <img src="https://stackoverflow.com/" alt="Alt Text" />

And if I have https://stackoverflow.com/ it should parse to

The thing is, this doesn’t work, when I parse the image, later the src inside img parses to src="<a href="https://stackoverflow.com/"></a>"

These are my regex:

parsedString = parsedString.replace(/![([^]]+)](([^)]+))/gim, '<img src="$2" alt="$1" target="_blank" />')
parsedString = parsedString.replace(/b(https?://[^s]+)b/gim, '<a href="$1" target="_blank">$1</a>')

My links work fine but I can’t see the images that way. I thought maybe detecting if a url starts with " to not parsing it to an anchor.

When trying to get user input in HTML form using .value it is not returning the live value, but instead the default

In JS and HTML I am trying to make it that when a user inputs their email address and clicks a login button the JS program will alert() the email address that they inputted.
Instead, all the program does is alert the default value, value="[email protected]", and not the value that the user inputted. I read something about getting the default value vs. the new value, but it never quite explained. Is it that .value needs to be different?

FYI, the snippet doesn’t work

function myFunction() {
 var x = document.getElementById("emailData").value;
 alert(x)
}
document.getElementById("loginButton").onclick = myFunction();
<ion-icon name="mail-outline"></ion-icon>
<input type="email" id="emailData" value="[email protected]" required>
<label for="">Email</label>

<button id="loginButton">Log in</button>

How can I make an array of objects out of a form?

I have a form with the following structure:

<form>
  <div>
     <div>
        <FormLabel />
        <FormSelect />
     </div>
     <fieldset>
       <legend> ---- </legend>
       <div>
          <FormLabel />
          <input></input>
       </div>
       <div>
         <FormLabel />
         <input type='radio'></input>
       </div>
     </fieldset>
     <ProductOrder /> 
     <div>
        <span>+</span>
     </div>
</form>

As you can see, I’m using React, the problem that I can’t solve is this:
When the user clicks in the span, a new Component spawn, this component is just another set of inputs.

The API that i made for this App needs the following object:

{
  providerId : (selectedProviderId),
  isPayed: (boolean),
  orderArrive: (some Date),
  items: [
     { object of each item},
     { the user want to add}
  ]
}

Each ProductOrder component the user adds, has to be each item, here is the problem, I haven’t been able to find a solution to separate each ProductOrder into an object and “push” it to an array.

I’ve been tried to create react states to store the object, but how do I separate these inputs from the others to create the object, and how do I make an object for each set of inputs?

Big Problem :on reload Dark mode flickers a white background

when the dark mode is enabled and the page is reloaded for some reason, for example, if the user deliberately reloads the page or submits a form, there’s a flicker of white background all over the page before it turns dark.

It only lasts a fraction of a second. It simply does not appear professional.

all details on codepen: flicker of white background

help me please

html :

<div class='WPmodedark'><input class='check' id='WPmodedark' title='Mode Dark' type='checkbox'/>  
<label class='WPim' for='WPmodedark'>  
<svg class='WPOM' viewBox='0 0 24 24'><path d='M19.1 17.5c-3.3 1.4-7.1-.2-8.5-3.5-1.4-3.3.2-7.1 3.5-8.5.2-.1.5-.2.7-.3-1.6-.4-3.2-.3-4.8.4C6 7.3 4 12 5.7 16c1.7 4.1 6.4 6 10.5 4.3 1.7-.7 3-1.9 3.8-3.4-.3.3-.6.4-.9.6z'/></svg>
<svg class='WPCM' viewBox='0 0 24 24'><path d='M18.1 5.1c0 .3-.1.6-.3.9l-1.4 1.4-.9-.8 2.2-2.2c.3.1.4.4.4.7zm-.5 5.3h3.2c0 .3-.1.6-.4.9s-.5.4-.8.4h-2v-1.3zm-6.2-5V2.2c.3 0 .6.1.9.4s.4.5.4.8v2h-1.3zm6.4 11.7c-.3 0-.6-.1-.8-.3l-1.4-1.4.8-.8 2.2 2.2c-.2.2-.5.3-.8.3zM6.2 4.9c.3 0 .6.1.8.3l1.4 1.4-.8.9-2.2-2.3c.2-.2.5-.3.8-.3zm5.2 11.7h1.2v3.2c-.3 0-.6-.1-.9-.4s-.4-.5-.4-.8l.1-2zm-7-6.2h2v1.2H3.2c0-.3.1-.6.4-.9s.5-.3.8-.3zM6.2 16l1.4-1.4.8.8-2.2 2.2c-.2-.2-.3-.5-.3-.8s.1-.6.3-.8z'/><circle cx='12' cy='11' r='4'/></svg>
</label> 
</div>
<script crossorigin='anonymous' integrity='sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=' src='https://code.jquery.com/jquery-3.6.0.min.js'/>

css :

/*-------- Night Mode Feature --------*/   
.WPmodedark {height: 34px;}  
.WPmodedark svg { width: 24px;  height: 24px;vertical-align: -6px; }  
.WPmodedark svg path {fill: $(white.color.wp);}.WPNM .WPmodedark svg path {fill: $(black.color.wp);}
.WPmodedark .check:checked~.NavMenu {opacity: 1;  visibility: visible; z-index: 2;}  
.WPim { cursor: pointer;  display: block; padding: 6px 20px 8px 20px; background-position: center;}  
.WPim:hover {background:rgba(0,0,0,0.2)radial-gradient( circle , transparent   2% , rgba( 0 , 0 , 0 , .2 )   2% );}    
.WPmodedark .WPim .WPOM , .WPmodedark .check:checked~.WPim .WPCM {display: block;background: olivedrab;}  .check , .WPmodedark .WPim .WPCM ,.WPmodedark .check:checked~.WPim .WPOM {display: none;} 
/* -- content --*/ 
body.WPNM , body.WPNM div.page_body {background:#101a00!important;}

script :


window.addEventListener('DOMContentLoaded', function () {
/*-- DM WP --*/
$("body").toggleClass(localStorage.toggled),
    $("#WPmodedark").on("click", function () {
        "WPNM" != localStorage.toggled
            ? ($("body").toggleClass("WPNM", !0), (localStorage.toggled = "WPNM"), $(".section-center").css("display", "block"))
            : ($("body").toggleClass("WPNM", !1), (localStorage.toggled = ""), $(".section-center").css("display", ""));
    }),
    $("body").hasClass("WPNM") ? $("#WPmodedark").prop("checked", !0) : $("#WPmodedark").prop("checked", !1);

});

JavaScript While Statement Continuing to Run when Condition is False

I am new to JavaScript and web development so I apologize if this has already been answered. I am making a webpage with an image carousel. I have added buttons to go to the next and previous images as well as an automatic scrolling feature; these both work as intended. The issue comes in when I am trying to disable the automatic scrolling upon the pressing of either of the buttons. When I press a button, the automatic scrolling continues. My code is below.

<script>
            var carousel = document.getElementById("carousel");
            var width = carousel.offsetWidth;
            var scrollDelay = 2.5; //Amount of time between each slide in the carousel (seconds)
            var interrupted = false;

            function next() {
                carousel.scrollBy({ 
                    left: width, 
                    behavior: 'smooth' 
                });
                interruped = true;
            }
            function back() {
                carousel.scrollBy({ 
                    left: (width * -1), 
                    behavior: 'smooth'
                });
                interruped = true;
            }
            
            var i = 0;
            while (i < 100 && !interrupted) {
                i++;
                autoScroll();
            }
                
            function autoScroll() {
                    setTimeout(function() {
                        next();
                    }, scrollDelay * 1000 * i)
            }
        </script>

I believe my issue has something to do with the while statement. When I press the button, it changes the value of interrupted to true, which should end the loop, but it does not. Does anyone know why this might be happening?

I would like to add a a specific color to each level of google organisation chart

Hi everyone I am current baffled by this issue i am having with google organisational chart.

I want to add the same background color to all nodes on the same level / row. Is there a api to do that.

google.setOnLoadCallback(drawChart);
      function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Name');
        data.addColumn('string', 'Manager');
        data.addColumn('string', 'ToolTip');

        data.addRows([
          [{v:'Mike', f:'Mike<div style="color:red; font-style:italic">President</div>'}, '', 'The President'],
          [{v:'Jim', f:'Jim<div style="color:red; font-style:italic">Vice President</div>'}, 'Mike', 'VP'],
          ['Alice', 'Mike', ''],
          ['Bob', 'Jim', 'Bob Sponge'],
          ['Carol', 'Bob', '']
        ]);
          
        data.setRowProperty(0, 'style', 'background-color:red; border: 1px solid green');

        var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
        chart.draw(data, {allowHtml:true});
      }

here i can set 1 node at a time, how can i get all nodes on the same level/row to be the same background color?

How do I finish this autocomplete search bar to work with the FDIC API?

I want to complete a search bar that autocompletes with FDIC bank name data.I’ve got the following code which aims to create an autocomplete search bar from the FDIC bank call report API

import './App.css';
import './custom.css';
import axios from 'axios';
import { useEffect, useState } from 'react';
function App() {
  const [users, setUsers] = useState([]);
  const [text, setText] = useState('');
  const [suggestions, setSuggestions] = useState([]);
  useEffect(() => {
    const loadUsers = async () => {
      const response = await axios.get('https://banks.data.fdic.gov/api/institutions?sort_by=NAME&sort_order=DESC&limit=5&offset=0&format=json&download=false&filename=data_file');
      setUsers(response.data.data)
    }
    loadUsers();

  }, [])
  const onSuggestHandler = (text) => {
    setText(text);
    setSuggestions([]);
  }
  const onChangeHandler = (text) => {
    let matches = []
    if (text.length > 0) {
      matches = users.filter(user => {
        const regex = new RegExp(`${text}`, "gi");
        return user.email.match(regex)
      })
    }
    console.log('matches', matches)
    setSuggestions(matches)
    setText(text)
  }
  return (
    <div className="container">

      <input type="text" className="col-md-12 input" style={{ marginTop: 10 }}
        onChange={e => onChangeHandler(e.target.value)}
        value={text}
        onBlur={() => {
          setTimeout(() => {
            setSuggestions([])
          }, 100);
        }}
      />
      {suggestions && suggestions.map((suggestion, i) =>
        <div key={i} className="suggestion col-md-12 justify-content-md-center"
          onClick={() => onSuggestHandler(suggestion.email)}
        >{suggestion.email}</div>
      )}
    </div>
  );
}

export default App;

The problem is
const response = await axios.get('https://banks.data.fdic.gov/api/institutions?sort_by=NAME&sort_order=DESC&limit=5&offset=0&format=json&download=false&filename=data_file'); setUsers(response.data.data)
in this line I am not sure how to link the API in such a way that the autocomplete suggestion updates as I continue to type.

This is the API docs https://banks.data.fdic.gov/docs/#/Structure/searchInstitutions

the Easy Search allows for a user to do a fuzzy search but I am not sure how to integrate this into my app with the autocomplete. Any guidance would be appreciated.

I’ve tried several tutorials on autocomplete searchbar but non deal with this kind of API.

What is the best practice for an application that provides an embeddable widget?

So take intercom, drift or any 3rd party interactive widget.

The end result being a snippet of code, that then builds an iframe? and controls sizing while allowing for cross origin requests. Is this really the best way to do this when offering an embeddable widget from SiteA.com to SiteB.com ?

It’s my understanding that if I wanted to offer an embedded widget, I would create javascript snippet that added an iframe to the host’s webpage, that iframe then displays the component. Only caveats I see is sizing of a responsive widget would also have to be in the snippet.

Curious if this is the standard way to do this, or if there is something better.

Slash Command in Discord.js v14 not executing

I’m trying to run a command named /setup that grants 3 options. It displays the 3 options, however it seems as if the interaction isn’t passed down to the execute. I’m pretty sure it’s my InteractionCreate, however I’m new to the js scene but have some experience. I could be only handling buttons/modals and not the actual command in my interaction.

setup.js

const { PermissionFlagsBits, SlashCommandBuilder } = require('discord.js');
const unbanModal = require('../Modals/unbanModal.js');

module.exports = {
    data: new SlashCommandBuilder()
        .setName('setup')
        .setDescription('Setup the bot for your server')
        .addChannelOption(option => 
            option.setName('logchan')
            .setDescription('Channel to log moderation actions')
            .setRequired(false)
        )
        .addChannelOption(option => 
            option.setName('appchan')
            .setDescription('Channel to log applications')
            .setRequired(false)
        )
        .addChannelOption(option => 
            option.setName('modalchan')
            .setDescription('Channel to send the appeal application')
            .setRequired(false)
        )
        .setDefaultMemberPermissions(PermissionFlagsBits.KickMembers),
    async execute(interaction) {
        console.log('executing setup');
        try {
            const logChan = interaction.options.getChannel('logchan');
            const appChan = interaction.options.getChannel('appchan');
            const modChan = interaction.options.getChannel('modalchan');
        
            if (logChan || appChan || modChan) {
                console.log('executing unbanModal');
                await unbanModal.execute(interaction);
            } else {
                console.log('No channel was provided');
                interaction.reply({content: 'You must specify at least one channel.', ephemeral: true});
            }
        
        } catch(err) {
            console.log(err);
            interaction.reply({content: 'An error occurred while trying to get the channels from your request.', ephemeral: true});
        }        
    }
}

main.js

const fs = require('node:fs');
const path = require('node:path');
const { Client, Collection, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.MessageContent] });
const { botToken } = require('./Src/Credentials/Config.json');

client.commands = new Collection();
client.modals = new Collection();
client.buttons = new Collection();

console.log('client.buttons:', client.buttons);
  

const modalsDir = path.join(__dirname, 'Src', 'Modals');
const eventsPath = path.join(__dirname, 'Src', 'Events');
const commandsPath = path.join(__dirname, 'Src', 'MessageCommands');
const buttonsDir = path.join(__dirname, 'Src', 'Buttons');
console.log('buttonsDir:', buttonsDir);


const commandFiles = fs.readdirSync(commandsPath).filter(file => file.endsWith('.js'));
const eventFiles = fs.readdirSync(eventsPath).filter(file => file.endsWith('.js'));
const buttonFiles = fs.readdirSync(buttonsDir).filter(file => file.endsWith('.js'));
console.log('buttonFiles:', buttonFiles);
const modalFiles = fs.readdirSync(modalsDir).filter(file => file.endsWith('.js'));

for (const file of commandFiles) {
    const filePath = path.join(commandsPath, file);
    const command = require(filePath);

    if ('data' in command && 'execute' in command) {
        client.commands.set(command.data.name, command);
        console.log(`[INFO] Loaded command ${command.data.name}`);
    } else {
        console.log(`[WARNING] The command at ${filePath} is missing either the 'data' or 'execute' property.`);
    }
}

for (const file of eventFiles) {
    const filePath = path.join(eventsPath, file);
    const event = require(filePath);

    if (event.once) {
        client.once(event.name, (...args) => event.execute(...args));
    } else {
        client.on(event.name, (...args) => event.execute(...args));
    }
}

for (const file of buttonFiles) {
    try {
        const button = require(path.join(buttonsDir, file));
        console.log(`[INFO] Loaded button: ${button.name}`);
        client.buttons.set(button.name, button);
    } catch (error) {
        console.log(`[WARNING] Error loading button at ${path.join(buttonsDir, file)}: ${error}`);
    }
}
console.log('[INFO] CLIENT.buttons:', client.buttons);

for (const file of modalFiles) {
    const modal = require(path.join(modalsDir, file));
    client.modals.set(modal.name, modal);
    console.log(`[INFO] Loaded modal: ${modal.name}`);
}

async function startApp() {
    console.log("Starting...");
    try {
        await client.login(botToken);
        console.log(`Successfully logged in ${client.user.tag}`);
    } catch (error) {
        console.log(`Failed to login | ${error}`);
        process.exit(1);
    }
}

startApp();

module.exports = {
    client
}

interactionCreate.js

const { Client, Collection, Events, GatewayIntentBits } = require('discord.js');
const client = new Client({ intents: [GatewayIntentBits.Guilds, GatewayIntentBits.GuildMembers, GatewayIntentBits.GuildMessages, GatewayIntentBits.GuildMessageReactions, GatewayIntentBits.MessageContent] });

module.exports = {
    name: Events.InteractionCreate,
    async execute(interaction) {
        //if (!interaction.isChatInputCommand()) return;

        if (interaction.isModalSubmit()) {
            const modalName = interaction.customId;
            console.log('modalName:', modalName);
            try {
                console.log('client.modals:', client.modals);
                const modalEvent = client.modals.get(modalName);
                if (!modalEvent) return;


            } catch (error) {
                console.log('Error getting modal:', error);
                console.log('client.modals:', client.modals);
                console.log('modalName:', modalName);
            }
            const modalEvent = client.modals.get(modalName);
        
            if (!modalEvent) return;
    
            try {
                await modalEvent.execute(interaction);
            } catch (error) {
                console.error(`Error executing modal event "${modalName}":`, error);
                interaction.reply({ content: 'An error occurred while executing this command.', ephemeral: true });
            }
        } else if (interaction.isButton()) {
            const buttonName = interaction.customId;
            console.log('buttonName:', buttonName);
            const buttons = client.buttons;
            if (!buttons) {
                console.log('No buttons found');
                return;
            }
            const buttonEvent = buttons.find(btn => btn.name === buttonName);
            if (!buttonEvent) {
                console.log(`Button event ${buttonName} not found`);
                return;
            }

            try {
                await buttonEvent.execute(interaction);
            } catch (error) {
                console.error(`Error executing Button event "${buttonEvent}":`, error);
                interaction.reply({ content: 'An error occurred while executing this command.', ephemeral: true });
            }
        }
    }
};

how to update a dialog from another dialog

I have a jquery dialog and inside that dialog an option to edit a field and that option shows another dialog for editing, what I want is that when I edit the second dialog it updates my first dialog, but the dialogs are in different files.

Dialog 1:
$(“#dialogComponentes”).html(obj.form).dialog({

    title: obj.titulo,
    width: dWidth,
    height: dHeight,
    modal: true,
    position: {
        my: "center",
        at: "center",
        of: $("#dvDialogUbicacionElementos")
    },
    buttons: [{
           id: 'btnGrabar',
           text: 'Grabar',
           click: function() {
                grabarComponentes();                
           }
    },
    {
            id: 'btnCancelar',
            text: 'Cancelar',
            click: function() {
                $(this).dialog("close");
            idComponente = -1;
            }
        }
    ],
     close: function() {
         $(this).dialog("close");
        idComponente = -1;
    },
         dialogClass: "overflow-fix"
});

dialog 2:

$(“#dvDialogEdicionArchivo”).html(obj.formulario).dialog({

                    title: "Editar archivo",
                    width: 400,
                    height: 200,
                    modal: true,
                    position: {
                        my: "center",
                        at: "center",
                        of: $("#dvDialogUbicacionElementos"),
                    },
                    buttons: [
                        {
                            text: "Grabar",
                            id: "btnEdicionArchivo",
                            click: function () {
                                edicionArchivoAdjunto();
                            },
                        },
                        {
                            text: "Cancelar",
                            id: "btnCancelarArchivo",
                            click: function () {
                                $(this).dialog("close");
                            },
                        },
                    ],
                });

Loading values from localstorage into typescript object

I’m making a preferences object in Typescript, and I want it to be smart enough to enforce typings in the code. Everything will be stored in localStorage which means ultimately the values will all be strings. Here’s a simplified example:

type ONOFF = 'ON' | 'OFF';
type DIRECTION = 'NORTH' | 'SOUTH' | 'EAST' | 'WEST';

enum KEY {
  DESTINATION = 'destination',
  ORIGIN = 'origin',
  LIGHTMODE = 'lightMode',
};


interface IPreferences {
  [KEY.DESTINATION]: DIRECTION; 
  [KEY.ORIGIN]: DIRECTION;
  [KEY.LIGHTMODE]: ONOFF;
};

const defaults: IPreferences = {
  destination: 'NORTH', 
  origin: 'SOUTH', 
 lightMode: 'ON'
};

That works fine in code. There’s autocomplete for every preference anywhere in the app.

I’m running into an issue though with loading in the values from localStorage.

const stored : Partial<IPreferences> = {};

Object.values(KEY).forEach((preference) => {
  const value = localStorage.getItem(preference);
  if(value) {
    stored[preference] = value;
  }
});

The stored[preference] = value; line errors with Type 'string' is not assignable to type 'undefined'.

Now I could get around this error by not looping through the available keys and hardcoding each one, ie:

const hardCoded : Partial<IPreferences> = {
  [KEY.DESTINATION]: localStorage.getItem(KEY.DESTINATION) as ONOFF;
}

but that’s not ideal.