When requesting a file for ajax, ~/filename isn’t giving me the file, instead its giving me an error

When I run the code below, it doesn’t return anything, but when I check Network tab in the dev tools, I’m greeted with the code for an html error page (since I’m using repl.it)

function onSubmit(e) {
    e.preventDefault()
    if(year.value === "" || cat.value === "") {
        msg.textContent = "Please fill out the fields"
        msg.classList.add("error");
    } else {
        msg.textContent = ""
        msg.classList.remove("error");
        const catvalue = cat.value
        $.ajax({
          type: "POST",
          url: "~/mapsinterpeter.py", 
          data: { param: [catvalue, year.value]} 
        }).done(function( e ) {
           console.log(e)
           
        });
        ;
        year.value = ""
        cat.value = ""
    } 
}

Styling order of Material UI

I’ve spent like 10 hours on customization to understand it perfectly but it makes me headache as I go on.

I’m styling outlined TextField, specifically its label and border.
I thought it wouldn’t be problematic if I use sx prop to customize but it didn’t work well as I had expected.

const One = () => (
  <div>
    <TextField
      id="outlined-basic"
      label="One"
      variant="outlined"
      sx={{
        "& .MuiOutlinedInput-root": {
          borderRadius: 0
        },

        "& .MuiInputLabel-root": {
          color: "orange"
        },

        "& .Mui-focused .MuiOutlinedInput-notchedOutline": {
          borderColor: "orange"
        }
      }}
    />
  </div>

I want label to be orange always, and border to be orange when focused. But when I focus on the TextField, label and border go back to blue. But border-radius works well.

I inspected the result and it seemed like default style was inserted again when the component was focused. I don’t get it because I think it should have been inserted earlier, like when the TextField mounted. Why is sx prop not overriding the default style?

enter image description here

https://codesandbox.io/s/material-ui-customization-zg5v5v?file=/src/components/One.jsx

React, problem with my Todo list app, my search engine only finds notes on the page I’m on

my notes app has a pagination which works perfectly, the problem is in the search engine, which only looks for notes from the page I’m on, for example, if I’m on page 2 and I look for a note on page 2, it shows it, however if the note is on a different page, it doesn’t show it, it doesn’t find it.

I know where the problem is but I’m not sure how to solve it, I’m a bit new to React and I was asking for your help.

I was able to do my pagination with the package react-paginate here is the documentation https://www.npmjs.com/package/react-paginate

My code:

Component App.js

import { useState, useEffect } from "react";
import { nanoid } from 'nanoid';
import './App.css';
import Search from "./components/Search";
import Header from "./components/Header";
import Pagination from "./components/Pagination";

const App = () => {
  const [notes, setNotes] = useState([]);
  const [searchText, setSearchText] = useState('');
   const [darkMode, setDarkMode] = useState(false); 
   //Se encarga de mostrar la nota para escribir 
   const [showNote, setShowNote] = useState(true); //eslint-disable-line
  useEffect(() => {
    const saveNotes = JSON.parse(localStorage.getItem('notes-data'));
    if (saveNotes){
      setNotes(saveNotes);
    }
    
  }, []);
  useEffect(() => {
    localStorage.setItem('notes-data', JSON.stringify(notes))
  },[notes])

  const addNote = (inputText, text) => { 
    const date = new Date();
    const newNote = {
      id: nanoid(),
      title: inputText,
      text: text,
      date: date.toLocaleString()
      
    }
    const newNotes = [newNote, ...notes];
    setNotes(newNotes)
  }
  const deleteNote = (id) => {
    var response = window.confirm("Are you sure?");
    if (response){
      const notesUpdated = notes.filter((note) => note.id !== id)
      setNotes(notesUpdated);
    }
  }
  return (
    <div className={darkMode ? 'dark-mode' : ''}>

    <div className="container">
      <Header 
        handleToggleTheme={setDarkMode}
      />
      <Search 
        handleSearchNote={setSearchText}
        setShowNote={setShowNote}
        />
      <Pagination 
        data={notes} 
        handleAddNote={addNote}
        handleDeleteNote={deleteNote}
        searchText={searchText}
        />
    </div>
    </div>
  )
}

export default App;

Component Pagination.js

import React, { useEffect, useState } from 'react'
import ReactPaginate from 'react-paginate';
import '../styles/Pagination.css';
import NoteList from './NoteList';
import { MdSkipPrevious, MdSkipNext } from 'react-icons/md';


const Pagination = (props) => {
  const { data, searchText, handleAddNote, handleDeleteNote } = props;
    
  // We start with an empty list of items.
  const [currentItems, setCurrentItems] = useState([]);
  const [pageCount, setPageCount] = useState(0);
  // Here we use item offsets; we could also use page offsets
  // following the API or data you're working with.
  const [itemOffset, setItemOffset] = useState(0);
    const itemsPerPage = 9;

  useEffect(() => {
    // Fetch items from another resources.
    const endOffset = itemOffset + itemsPerPage;
    console.log(`Loading items from ${itemOffset} to ${endOffset}`);
    setCurrentItems(data.slice(itemOffset, endOffset));
    setPageCount(Math.ceil(data.length / itemsPerPage));
  }, [itemOffset, itemsPerPage, data]);

  // Invoke when user click to request another page.
  const handlePageClick = (event) => {
  const newOffset = (event.selected * itemsPerPage) % data.length;
  console.log(
    `User requested page number ${event.selected}, which is offset ${newOffset}`
  );
  setItemOffset(newOffset);
  };

  return (
    <>
      <NoteList 
       notes={currentItems.filter((noteText) => 
          noteText.title.toLowerCase().includes(searchText)
        )}
        handleAddNote={handleAddNote}
        handleDeleteNote={handleDeleteNote}
      />
      <div className="pagination-wrapper">

      <ReactPaginate
        breakLabel="..."
        nextLabel={<MdSkipNext 
          className='icons'
        />}
        onPageChange={handlePageClick}
        pageRangeDisplayed={3}
        pageCount={pageCount}
        previousLabel={<MdSkipPrevious 
          className='icons'
        />}
        renderOnZeroPageCount={null}
        containerClassName="pagination"
        pageLinkClassName="page-num"
        previousLinkClassName="page-num"
        nextLinkClassName="page-num"
        activeLinkClassName="activee boxx"
      />
      </div>
    </>
  );
}

export default Pagination;


Component NoteList.js

import React from 'react'
import Note from './Note'
import '../styles/NoteList.css'
import AddNote from './AddNote'

const NoteList = ({ notes, handleAddNote, handleDeleteNote }) => {
  return (

    <>
        <div className="add-notes-wrapper">
            <AddNote 
                handleAddNote={handleAddNote}       
            />
        </div>
        <div className='notes-list'>
                {notes.map((note => 
                    <Note 
                        key={note.id}
                        id={note.id}
                        title={note.title}
                        text={note.text}
                        date={note.date}
                        handleDeleteNote={handleDeleteNote}
                    />
                ))}     
        </div>
    </>
  )
}

export default NoteList;

Component Search.js

//import React, { useState } from 'react'
import {MdSearch, MdAdd} from 'react-icons/md'
import '../styles/Search.css'


const Search = ({ handleSearchNote, setShowNote }) => {
    const handleShowAddNote = () => {
        if (setShowNote){ 
            let addNote = document.querySelector('.new');
            addNote.classList.add('wobble-horizontal-top')
            addNote.style.display='flex';
            document.querySelector('.notes-list').style.display='none';
            document.querySelector('.pagination').style.display='none';
        }
    }
  return (
        <div className='search'>
            <div className="input-wrapper">
                <MdSearch 
                    className='icon search-icon'
                /> 
                <input 
                    type="text" 
                    placeholder='¿Qué nota estás buscando?'
                    onChange={(event) => handleSearchNote(event.target.value) }
                />
            </div>
            <div className="btn-wrapper-search">
                <button 
                    className='btn-addNote'
                    onClick={handleShowAddNote}>
                    Nueva Nota
                </button>
                <MdAdd 
                    className='icon add-icon'
                />
            </div>
        </div>
  )
}

export default Search

The problem is in the component Pagination.js because I’m filtering the notes on each page with the currentItems variable, if I did it with the data variable it would work, but then it would show all the notes, and I don’t want that, I currently want to show 9 notes per page.

greetings and thanks in advance.

Scrolling on Mobile Accordion Menu NOT Possible

I’m working on mobile menu adopting this piece of code, menu is nearly finished and all was working fine until I tested this on real mobile device.
All tabs are working perfectly but opens immediately when touched so scroll is not possible because whenever i touch the screen the tabs opening not allowing me to scroll.

I’ve removed e.preventDefault(); function and I was able to tap and scroll on the submenu pages when the menu is fully opened, but this is not how this menu should work.
I would like to be able to scroll the menu when finger is sliding over the screen and be able to open menu tabs when tapped. Can you guys show me the right path please?

PS.
I’ve added a bit of margin at the top so when you open this on bigger mobile phones you will have some content to scroll.

;(function($, window, document, undefined) {
  var pluginName = "jqueryAccordionMenu";
  var defaults = {
    speed: 300,
    showDelay: 0,
    hideDelay: 0,
    singleOpen: true,
    clickEffect: true
  };
  
  function Plugin(element, options) {
    this.element = element;
    this.settings = $.extend({}, defaults, options);
    this._defaults = defaults;
    this._name = pluginName;
    this.init();
  }
  
  $.extend(Plugin.prototype, {
    init: function() {
      this.openSubmenu();
      this.submenuIndicators();
    },
    openSubmenu: function() {
      $(this.element).children('ul').find('li').bind('click touchstart', function(e) {
        e.stopPropagation();
        e.preventDefault();
        if ($(this).children('.submenu').length > 0) {
          if ($(this).children('.submenu').css('display') == 'none') {
            $(this).children('.submenu').delay(defaults.showDelay).slideDown(defaults.speed);
            $(this).children('.submenu').siblings('a').addClass('submenu-indicator-minus');
            if (defaults.singleOpen) {
              $(this).siblings().children('.submenu').slideUp(defaults.speed);
              $(this).siblings().children('.submenu').siblings('a').removeClass('submenu-indicator-minus');
            }
            return false;
          } else {
            $(this).children('.submenu').delay(defaults.hideDelay).slideUp(defaults.speed);
          }
          
          if ($(this).children('.submenu').siblings('a').hasClass('submenu-indicator-minus')) {
            $(this).children('.submenu').siblings('a').removeClass('submenu-indicator-minus');
          }
        }
        window.location.href = $(this).children('a').attr('href');
      })
    },
    submenuIndicators: function() {
      if ($(this.element).find('.submenu').length > 0) {
        $(this.element).find('.submenu').siblings('a').append('<span class="submenu-indicator">+</span>');
      }
    },
  });
  $.fn[pluginName] = function(options) {
    this.each(function() {
      if (!$.data(this, 'plugin_' + pluginName)) {
        $.data(this, 'plugin_' + pluginName, new Plugin(this, options));
      }
    });
    return this;
  }
})(jQuery, window, document);

jQuery('#jquery-accordion-menu').jqueryAccordionMenu();
* {
  box-sizing: border-box;
}
body {
  background: #f0f0f0;
  margin: 0;

}
.content {
  width: 100%;
  margin: 100px 0;
}
#demo-list a {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}
.jquery-accordion-menu, .jquery-accordion-menu * {
  font-family: 'Open Sans', sans-serif;
  box-sizing: border-box;
  outline: 0;
}


.jquery-accordion-menu {
  width: 100%;
  float: left;
  position: relative;
}

.jquery-accordion-menu .jquery-accordion-menu-footer, .jquery-accordion-menu .jquery-accordion-menu-header {
  width: 100%;
  height: 50px;
  padding-left: 22px;
  float: left;
  line-height: 50px;
  font-weight: 600;
  color: #f0f0f0;
  background: #414956;
}

.jquery-accordion-menu ul {
  margin: 0;
  padding: 0;
  list-style: none;
}

.jquery-accordion-menu ul li {
  width: 100%;
  display: block;
  float: left;
  position: relative;
}

.jquery-accordion-menu ul li a {
  width: 100%;
  padding: 14px 22px;
  float: left;
  text-decoration: none;
  color: #f0f0f0;
  font-size: 13px;
  background: #414956;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  transition: color .2s linear, background .2s linear;
}

.jquery-accordion-menu>ul>li.active {
  color: #fff;
  background: #3b424d;
}

.jquery-accordion-menu>ul>li>a {
  border-bottom: solid 1px #3b424d;
}

.jquery-accordion-menu ul li a i {
  width: 34px;
  float: left;
  line-height: 18px;
  font-size: 16px;
  text-align: left;
}

.jquery-accordion-menu .submenu-indicator {
  float: right;
  right: 22px;
  position: absolute;
  line-height: 19px;
  font-size: 20px;
  transition: transform .3s linear;
}

.jquery-accordion-menu ul ul.submenu .submenu-indicator {
  line-height: 16px;
}

.jquery-accordion-menu .submenu-indicator-minus>.submenu-indicator {
  transform: rotate(45deg);
}

.jquery-accordion-menu ul ul.submenu, .jquery-accordion-menu ul ul.submenu li ul.submenu {
  width: 100%;
  display: none;
  position: static;
}

.jquery-accordion-menu ul ul.submenu li {
  clear:both;
  width: 100%;
}

.jquery-accordion-menu ul ul.submenu li a {
  width: 100%;
  float: left;
  font-size: 11px;
  background: #383838;
  border-top: none;
  position: relative;
  border-left: solid 6px transparent;
  transition: border .2s linear;
}

.jquery-accordion-menu ul ul.submenu>li>a {
  padding-left: 30px;
}

.jquery-accordion-menu ul ul.submenu>li>ul.submenu>li>a {
  padding-left: 45px;
}

.jquery-accordion-menu ul ul.submenu>li>ul.submenu>li>ul.submenu>li>a {
  padding-left: 60px;
}

.jquery-accordion-menu ul li .jquery-accordion-menu-label, .jquery-accordion-menu ul ul.submenu li .jquery-accordion-menu-label {
  min-width: 20px;
  padding: 1px 2px 1px 1px;
  position: absolute;
  right: 18px;
  top: 14px;
  font-size: 11px;
  font-weight: 800;
  color: #555;
  text-align: center;
  line-height: 18px;
  background: #f0f0f0;
  border-radius: 100%;
}

.jquery-accordion-menu ul ul.submenu li .jquery-accordion-menu-label {
  top: 12px;
}

.red.jquery-accordion-menu .jquery-accordion-menu-footer,.red.jquery-accordion-menu .jquery-accordion-menu-header,.red.jquery-accordion-menu ul li a {
    background: #ED5565
}

.red.jquery-accordion-menu>ul>li.active>a {
    background: #DA4453
}

.red.jquery-accordion-menu>ul>li>a {
    border-bottom-color: #DA4453
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">
  <div id="jquery-accordion-menu" class="jquery-accordion-menu red">
    <ul id="demo-list">
      <li class="active"><a href="#"><i class="fa fa-home"></i>Home </a></li>
      <li><a href="#"><i class="fa fa-glass"></i>Events </a></li>
      <li><a href="#"><i class="fa fa-file-image-o"></i>Gallery </a></li>
      <li><a href="#"><i class="fa fa-cog"></i>Services </a>
        <ul class="submenu">
          <li><a href="#">Web Design </a></li>
          <li><a href="#">Hosting </a></li>
          <li><a href="#">Design </a>
            <ul class="submenu">
              <li><a href="#">Graphics </a></li>
              <li><a href="#">Vectors </a></li>
              <li><a href="#">Photoshop </a></li>
              <li><a href="#">Fonts </a></li>
            </ul>
          </li>
          <li><a href="#">Consulting </a></li>
        </ul>
      </li>
      <li><a href="#"><i class="fa fa-home"></i>System </a></li>
      <li><a href="#"><i class="fa fa-suitcase"></i>Portfolio </a>
        <ul class="submenu">
          <li><a href="#">Web Design </a></li>
          <li><a href="#">Graphics </a><span class="jquery-accordion-menu-label">10 </span></li>
          <li><a href="#">Photoshop</a></li>
          <li><a href="#">Programming </a></li>
        </ul>
      </li>
      <li><a href="#"><i class="fa fa-user"></i>About </a></li>
      <li><a href="#"><i class="fa fa-envelope"></i>Contact </a></li>
    </ul>
  </div>
</div>

How to return the ‘data’ from fetch method in Javascript? [duplicate]

I am doing this homework for a job interview and I am stuck fetching the data from the api i created.

This works fine:

const getData = (url) => {
  fetch(url)
  .then(response => {
    return response.json();
  }).then(data => console.log(data))
}

getData('URL');

but then if I try to just return the data (instead of printing it inside the function), i get undefined:

const getData = (url) => {
  fetch(url)
  .then(response => {
    return response.json();
  }).then(data => {
    return data
  })
}

console.log(getData('URL'));

🙂

Eas build fails

I tried to do eas build --platform android in my expo app but I always encounter an error. Can you please help me to fix it? The error:

[stderr] 
FAILURE: Build failed with an exception.
[stderr] 
* Where:
[stderr] 
Script '/home/expo/workingdir/build/node_modules/react-native/react.gradle' line: 41
[stderr] 
* What went wrong:
[stderr] 
A problem occurred configuring project ':app'.
[stderr] 
> Could not find matching constructor for: java.io.File(File)

django – save list of base 64 images to database

i have a list of base64 images that i send from a react panel. images list look like below:

[
"data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkG",
"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAeAAAADkCAY"
]

Note: i remove most of the charachters because each index charachters is more than 2000 and it’s just a example of what i have.

so i want to save them in django model. my field for saving this list of images is this:

ArrayField(base_field=models.ImageField(upload_to='hotel_images/'))

so how should i convert list of base64 images to real images and save them to this ArrayField? or do you have a better way for saving this base64 images list?

Note: i convert images to base64 in react panel by code below:

const FR = new FileReader();

FR.addEventListener("load", function () {
   // FR.result is image converted to base64
   image = FR.result;
})

FR.readAsDataURL(img);

and i do this because i have a json that contains other fields like name and description so when i want to send this json with request body i should use JSON.stringify() for that and when i use JSON.stringify(), images field is turn to empty array and i have to convert images to base64. so if you have a solution for this problem, that could help too!

Final Note: my database is postgreSQL.

How to dynamically add and delete rows in a table through form

I’m trying to make the results of the inputs appear on the table, but I can’t, I’ve looked in several places and I don’t know what else to do, can you tell me what’s wrong?

This error appears in the terminal:
terminal

Error: src/app/components/template/form/form.component.html:67:25 – error TS2339: Property ‘item’ does not exist on type ‘FormComponent’.

67 {{item.endereco}}
~~~~

src/app/components/template/form/form.component.ts:7:16
7 templateUrl: ‘./form.component.html’,
~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component FormComponent.

Error: src/app/components/template/form/form.component.html:68:25 – error TS2339: Property ‘item’ does not exist on type ‘FormComponent’.

68 {{item.descricao}}
~~~~

src/app/components/template/form/form.component.ts:7:16
7 templateUrl: ‘./form.component.html’,
~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component FormComponent.

Angular:

import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';


@Component({
  selector: 'app-form',
  templateUrl: './form.component.html',
  styleUrls: ['./form.component.css']
})
export class FormComponent implements OnInit {

  formu: FormGroup;
  listData: any;

  constructor(
    private fb: FormBuilder){

      this.listData = [];

      this.formu = this.fb.group({
        codigo: ["", [Validators.required]],
        nome: ["", [Validators.required]],
        nascimento: "",
        endereco: "",
        descricao: ""
      })

  }

  public addItem(): void {
    this.listData.push(this.formu);
  }

  ngOnInit(): void {
  }
    
  }
<form [formGroup]="formu">
    <span>
    <label for="" class="form-label">Código*:</label>
    <br>
    <input type="text" formControlName="codigo" placeholder="0000">
    <div *ngIf="formu.get('codigo')?.errors?.['required'] && formu.get('codigo')?.touched">
    Código obrigatório 
    </div>
    <br>
    </span>
    <label for="" class="form-label">Nome*:</label>
    <br>
    <input type="text" placeholder="Nome Completo" formControlName="nome">
    <div *ngIf="formu.get('nome')?.errors?.['required'] && formu.get('nome')?.touched">
        Nome obrigatório
    </div>
    <br>
    <label for="" class="form-label">Data de Nascimento:</label>
    <br>
    <input type="date" formControlName="nascimento">
    <br>
    <label for="" class="form-label">Endereço:</label>
    <br>
    <input type="text" formControlName="endereco">
    <br>
    <label for="" class="form-label">Descrição:</label>
    <br>
    <textarea name="" id="" cols="30" rows="10" formControlName="descricao"></textarea>
    <br>
    <br>
    <button (click)="addItem()" class="btn btn-primary mb-3">Salvar</button>
</form>
<div>
    <table class="table table-success table-striped">
        <thead>
          <tr>
            <th scope="col"></th>
            <th scope="col">Código</th>
            <th scope="col">Nome</th>
            <th scope="col">Data de Nascimento</th>
            <th scope="col">Endereço</th>
            <th scope="col">Descrição</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <th scope="row">1</th>
            <td>0001</td>
            <td>Andressa Lima</td>
            <td>07/04/2004</td>
            <td>Rua das Palmeiras</td>
            <td>Gosta de ler</td>
          </tr>
          <tr>
            <th scope="row">2</th>
            <td>0002</td>
            <td>Maria Laurentino</td>
            <td>28/03/1969</td>
            <td>Rua JK</td>
            <td>É detalhista</td>
          </tr>
          <tr>
            <th scope="row" *ngFor="let item of listData"></th>
            <td><span>{{item.codigo}}</span></td>
            <td><span>{{item.nome}}</span></td>
            <td><span>{{item.nascimento}}</span></td>
            <td><span>{{item.endereco}}</span></td>
            <td><span>{{item.descricao}}</span></td>
          </tr>
        </tbody>
      </table>    
</div>

SocketIO: basic socket.broadcast.emit not excluding sender

I have made this very small basic socket-io app that moves an objects position for every user connected to my app. So if user A is moving the object, its moving for user B and
same for the other way.

My problem now is that the user that is moving the object also is receiving the event for a new position but that shouldnt be possible with socket.broadcast.emit('newPos', movementData); or am I missing something here?

Why is it not excluding the sender?

server.js

const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const io = new Server(server);

app.use(express.static(__dirname + '/public'))
app.get('/', (req, res) => {
  res.sendFile(__dirname + '/index.html');
});
//on connect
io.on('connection', (socket) => {
  //if we receive new movement send it to all clients expect sender
  socket.on('movement', function(movementData) {
    console.log('received');  
        socket.broadcast.emit('newPos', movementData);
  });
});

server.listen(3000, () => {
  console.log('listening on *:3000');
});

app.js

  // client
  var socket = io();
  // get object which holds position data
  var obj = app.getObjectByName('Cube');


  // save position data of user
  var x = obj.position.x;
  var y = obj.position.y;
  var z = obj.position.z;
  var oldPos;

  setInterval(function(){
    if(typeof oldPos !== "undefined" && (x !== obj.position.x || y !== obj.position.y || z !== obj.position.z)){
      // send new position to the server
      socket.emit('movement', {
        x: obj.position.x, y: obj.position.y, z: obj.position.z
      });
    }
    // erstelle / erneuere alte Position
     oldPos = obj.position.x;
     x = obj.position.x;
     y = obj.position.y;
     z = obj.position.z;
  },10000);

  //if we receive new data from the server then use it
  socket.on('newPos', function (pos) {
    console.log('receive new pos');
  });

Is this the rightway to redirect HTTP request to HTTPS in express server?

I´m currently working in my api and need that work in HTTPS Protocol/SSL so i did this.

https.createServer({
    key: fs.readFileSync(certKeySSLPath),
    cert: fs.readFileSync(certSSLPath)
}, app).listen(serverPORTHTTPS);

console.log('Server listening on PORT: ' + serverPORTHTTPS);

And it works completly fine, now the problem is that when i make a peticion without especific https or http protocol the request is not received so i think

Ok lets create a http server on port 80 and redirect all the trafic to https an tecnictlly it works but i´m not sure that is the best practic, someone can tell me if i´m rigth? Is this a good solucion thinking in production level?

This is my code

const app = express()

// * Redirecting HTTP Request To HTTPS

app.use((req,res,next) => {


    if(!req.secure){
        res.redirect("https://" + req.headers.host + req.url);
    }

    next()

})

// * Initializing HTTP

app.listen(serverPORTHTTP, (req,res) => {

    console.log('Server listening on PORT: ' + serverPORTHTTP);

});

// * Initializing HTTPS - SSL Server

https.createServer({
    key: fs.readFileSync(certKeySSLPath),
    cert: fs.readFileSync(certSSLPath)
}, app).listen(serverPORTHTTPS);

console.log('Server listening on PORT: ' + serverPORTHTTPS);

How to dynamically create a nested tree with depth 10 in JavaScript using a loop

I have a general tree class with: myTree = new Tree(string), appendChildNode(node), createChildNode(string), myTree.print() functions and myTree.name, myTree.children, etc attributes.

I know, I can create a tree depth (10) by hand like so:

// declare new tree
myTree = new Tree('Diagrams')
// adding nodes by hand here    
myTree.createChildNode('A1').createChildNode('A2').createChildNode('A3').createChildNode('A4').createChildNode('A5').createChildNode('A6').createChildNode('A7').createChildNode('A8').createChildNode('A9').createChildNode('A10')
myTree.print()

How would I do that programmatically using a for loop? Expected result depth 10:

Diagrams
 A1
  A2
   A3
    A4
     A5
      A6
       A7
        A8
         A9
          A10

Sorry, if this is a question that was answered before, I just cannot come up with a proper query to search for a solution to this. I think I am missing a syntax in JS for doing that. Info: I took the following general tree implementation: https://github.com/beforesemicolon/tutorials-files/blob/master/tree-generic.js

How to use NPM run build?

I created a vue3 website using Laravel 9 and Vue3. For the bundling of assets I am using the vite.
So for the development is good , I made the app. Now I want to deploy it.
I ran npm run build, it created a build folder in public. along with manifest.json

How am I gonna use it to make my application working on the live server ?

Below is the screenshot to file structure :

enter image description here

I want to append error message on div element

I am creating a sign-in page. I am currently busy with validation part in JS.

What I wan to know, if this is the correct way in doing it.

I did a logic that says if username is not entered error message should appear below the username stating Please add your username.

This is how I did the HTML element and js logic

HTML

<div class="container">

            <form action="" class="form">

            <div class="heading">
                <h1>Log In</h1>
                <p>Welcome to your finacial smart decision making</p>
            </div>
        
            <div class="row mb-3 align-item-center">
                <label for="formGroupEampleInput" class="form-label" id="username">Username</label>
                <input type="text" class="form-control" id="formGroupExampleInput" placeholder="User Name" required>
                <div class="username-error"></div>
            </div>
            <div class="row mb-3 align-item-center">
                <label for="formGroupEampleInput" class="form-label" id="password">Password</label>
                <input type="text" class="form-control" id="formGroupExampleInput" placeholder="Password" required>
                <div class="password-error"></div>
            </div>
            <button type="button" class="btn btn-primary" onclick ="validate()">Login</button>
        </form>

        <div class="side-image-container">

        </div>

JS

function validate(){

let username = document.querySelector("#username");
let password = document.querySelector("#username");
let usernameError = document.querySelector(".username-error");;
const createdEl = document.createElement("div");

 createdEl = document.createTextNode("Please add your username");

 if(!username){
    createdEl.appendChild(usernameError);
 }
}

Indication where the error message should apepar