Form POST request, not working. Undefined in Server (HTML,JS,EXPRESS,NODE,MONGODB)

Im working in an application with a front and a back end, my back end written in nodejs, using express, multer and mongoose, is working pretty fine when i send data through postman, but as soon as i try the same request in my client made with html,css and vanilla javascript, it doesnt work, it gives me the following error:

TypeError: Cannot read property ‘path’ of undefined (which is pointing towards my network file that manages connections for a specific entity).

Despite the error mentioned above, i’ve been trying to send a file and a string from the form in html to the network file in my node server, but i keep getting the same 2 or so errors in terminal.

Here is some code so you can understand better.

server.js (main entry point)

const express = require('express');
const app = express();
const server = require('http').Server(app);
const path = require('path');

const cors = require('cors');
const bodyParser = require('body-parser');
const db = require('./db');
const router = require('./network/routes');
const config = require('./config');

db(config.dbUrl);
app.use(cors());
app.use(express.json());
app.use(bodyParser.urlencoded({ extended: true }));

app.use(`${config.publicRoute}`, express.static(path.join(__dirname, 'public')));
server.listen(config.port, function() {});
console.log(`Application listen on ${config.host}${config.port}`);
router(app);

network.js (file that manages connections for “banner” entity)

const express = require('express');
const multer = require('multer');
const router = express.Router();
const response = require('../../network/response');
const controller = require('./controller');
const path = require('path');
const storage = multer.diskStorage({
    destination: function(req, file, cb) {
        cb(null, path.join(__dirname, '../../public/files'))
    },
    filename: function(req, file, cb) {
        cb(null, path.extname(file.originalname))
    }
})
const upload = multer({ storage: storage })

router.post('/', upload.single('file'), function(req, res) {

    console.log(req.body);
    controller.addBanner(req.body.name, req.file, req.file.path)
        .then((fullMessage) => {
            response.success(req, res, fullMessage, 201);
        })
        .catch(e => {
            response.error(req, res, 'Unexpected error', "Simulated Error", 400, e);
        });
});

router.get('/', function(req, res) {
    controller.getBanners()
        .then((banners) => {
            response.success(req, res, banners, 200);
        })
        .catch(e => {
            response.error(req, res, 'Internal Error', 500, e);
        })
});

router.delete('/:id', function(req, res) {
    controller.deleteBanner(req.params.id)
        .then(() => {
            response.success(req, res, `Imagen con id: ${req.params.id} ,eliminada`, 200);
        })
        .catch(e => {
            response.error(req, res, 'Internal Error', 500, e);
        })
});

module.exports = router;

panel.html (where the form that supposedly sends the post request lies)

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <!-- <meta http-equiv="Content-Security-Policy" content="default-src https://cdn.example.net; child-src 'none'; object-src 'none'"> -->
    <link rel="stylesheet" type="text/css" href="css/panel-style.css">
    <script defer src="panel-script.js"></script>
    <title>Panel de Control</title>
</head>

<body>
    <header>
        <img src="assets/mrvapeslogo.png" alt="mrvapes logo">
        <a href="index.html"></a>
    </header>
    <section>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="../components/banner/network.js" autocomplete="off" method="GET" target="_blank">
            <label for="user">Banners Activos</label><br/>
            <ul class="files-container">

            </ul>
        </form>
        <form accept-charset="UTF-8" enctype="multipart/form-data" action="http://localhost:3000/banner" autocomplete="off" method="POST" target="_blank">
            <div class="container">
                <div class="button-wrap">
                    <!-- <label class="button" for="upload">Subir</label> -->
                    <input type="text" id="name" placeholder="Nombre de Archivo" value="" name="name" required>
                    <input id="image" value="Subir" placeholder="Subir Archivo" type="file" required>
                    <button id="upload" name="send-post--request" value="post-request" type="submit">Enviar</button>
                    <!-- <input id="upload" type=" submit " value="Enviar " onclick="submit() "> -->
                </div>
            </div>
        </form>
    </section>
</body>

panel-script.js (client-side file that manages the logic for the http request)

const upload = document.getElementById("upload");
const image = document.getElementById("image");
const title = document.getElementById("name");

upload.addEventListener("click", (e) => {
    console.log('im in bro');
    e.preventDefault();
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            alert(xhr.response);
        }
    }
    xhr.open("POST", 'http://localhost:3000/banner', true);
    //xhr.setRequestHeader("Accept", "multipart/form-data");
    //xhr.setRequestHeader('Content-Type', 'multipart/form-data');
    var fileSent = {
        "name": title,
        "file": image
    };
    console.log(fileSent);
    xhr.send(fileSent);
    alert('Subida exitosa!');
})


function retrieve() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState === 4) {
            alert(xhr.response);
        }
    }
    xhr.open('get', 'http://localhost:3000/banner', true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
    xhr.send();
}

I’m all ears towards your suggestions, thanks in advance fellow developers.

Uncaught TypeError: Cannot read properties of null (reading ‘addEventListener’) at (index):72

let searchBtn = document.querySelector ( '#Search-btn');

let searchBar = document.querySelector ( ‘.search-bar-container’);

searchBtn.addEventListener(‘click’, () =>{

searchBtn.classlist.toggle('fa-times');
searchBar.classList.toggle('active');

});

let searchBtn = document.querySelector ( '#Search-btn');
let searchBar = document.querySelector ( '.search-bar-container');

searchBtn.addEventListener('click', () =>{

    searchBtn.classlist.toggle('fa-times');
    searchBar.classList.toggle('active');
});
@import url('https://fonts.googleapis.com/css2?family=Nunito:wght@200;300;400;600;700&display=swap');

:root {
    --orange:#ffa500;
    
}

*{
    font-family: 'Nunito', sans-serif;
    margin: 0; padding: 0;
    box-sizing: border-box;
    text-transform: capitalize;
    outline: none; border: none;
    transition: all .2s linear;
    text-decoration: none;
    
}

*::selection{
    background: var(--orange);
    color: #fff;
}

html{
    font-size: 62.5%;
    overflow-x: hidden;
    scroll-padding-top: 6rem;
    scroll-behavior: smooth;
}

header{
    position: fixed;
    top: 0; left: 0; right: 0;
    background: #333;
    z-index: 1000;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 2rem 9%;
}

header .logo {
    font-size: 2rem;
    font-weight: bolder;
    color: #fff;
    text-transform: uppercase;
}

header .logo span {
    color: var(--orange);
}

header .navbar a{
    font-size: 2rem;
    color: #fff;
    margin:0 .8rem;
}

header .navbar a:hover{
    color: var(--orange);
}

header .icons i{
    font-size: 2.5rem;
    color:#fff;
    cursor: pointer;
    margin-right: 2rem;
}

header .icons i:hover{
    color: var(--orange);
}

header .search-bar-container{
    position: absolute;
    top: 100%; left: 0; right: 0;
    padding: 1.5rem 2rem;
    background: #333;
    border-top: .1rem solid rgba(225, 225, 225, .2);
    display: flex;
    align-items: center;
    z-index: 1001;
    clip-path: polygon(0 0, 100% 0, 0 0);
}

header .search-bar-container.active{
    clip-path: polygon(0 0, 100% 0, 0 0);
}

#search-bar {

    width: 100%;
    padding: 1rem;
    text-transform: none;
    color: #333;
    font-size: 1.7rem;
    border-radius: 100rem;
}

header .search-bar-container label{
    color: #fff;
    cursor: pointer;
    font-size: 3rem;
    margin-left: 1.5rem;
}

header .search-bar-container label:hover {
    color: var(--orange);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Travel Agency</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    
<header>
    <a href="#" class="logo"> <span>T</span>ravel</a>

    <nav class="navbar">
        <a href="#home">home</a>
        <a href="#book">book</a>
        <a href="#package">package</a>
        <a href="#services">services</a>
        <a href="#review">review</a>
        <a href="#contact">contact</a>
    </nav>

    <div class="icons">
        <i class="fa fa-search" id="search-btn"></i>
        <i class="fa fa-user" id="login-btn"></i>
    </div>

    <form action="" class="search-bar-container">
        <input type="search" id="search-bar" placeholder="search here...">
        <label for="search-bar" class="fa fa-search" ></label>
    </form>

</header>

When I try to run my javascript code its give me an error. I do check my code and syntax twice i could not find the error please help me with that.

Using XPath to get an elmement in SVG

I am trying to get an element in an SVG file using XPath. I have tried the following code, but singleNodeValue is null. The doc seems to be correct, so I guess either evaluate() arguments or the XPath is wrong, but I cannot find anything wrong. Why doesn’t it work?

JavaScript

fetch('test.svg')
.then(response => response.text())
.then(data=>{
    const parser = new DOMParser();
    const doc = parser.parseFromString(data, "text/xml");
    console.log(doc);
    const res = doc.evaluate("//symbol[@label='square']", doc, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null);
    console.log(res.singleNodeValue);
})

SVG

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg">

    <symbol label ="square">
        <rect y="5" x="5" width="90" height="90" stroke-width="5" stroke="#f00" fill="#f00" fill-opacity="0.5" />
    </symbol>

</svg>

How do i trigger a link with no id via console

I am simply trying to trigger a link with no id via console. I have tried multiple scenarios and none seem to work. It is a link with lots of classes and no id.

$('.videoHolder').find('a.icon-play').trigger('click');
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="videoHolder hover">
  <div class="videoDisplay">

    <video class="persistentNativePlayer nativeEmbedPlayerPid" poster="data:image/png,%89PNG%0D%0A%1A%0A%00%00%00%0DIHDR%00%00%00%01%00%00%00%01%08%02%00%00%00%90wS%DE%00%00%00%01sRGB%00%AE%CE%1C%E9%00%00%00%09pHYs%00%00%0B%13%00%00%0B%13%01%00%9A%9C%18%00%00%00%07tIME%07%DB%0B%0A%17%041%80%9B%E7%F2%00%00%00%19tEXtComment%00Created%20with%20GIMPW%81%0E%17%00%00%00%0CIDAT%08%D7c%60%60%60%00%00%00%04%00%01'4'%0A%00%00%00%00IEND%AEB%60%82"
      id="pid_kaltura_player" kentryid="1_4u0ocu4u" kuiconfid="" kwidgetid="" kpartnerid="" preload="none" width="560" height="395" src="" style="position: absolute; left: 0px; top: 0px;"></video>
    <div class="videoShadow"></div>
    <div class="mwEmbedPlayer" id="kaltura_player" style=""></div>
  </div><a tabindex="-1" href="#" role="button" class="comp largePlayBtn  largePlayBtnBorder icon-play" aria-label="Play clip" data-order="1" data-plugin-name="largePlayBtn" style="display: flex; opacity: 1;">Mylink</a></div>

while clicking local push notification how to navigate and reload a page in flutter

Hi iam new user in flutter app. I need while clicking the notification navigate and reload the page. can you please suggest how to navigate and reload the page while clicking the notification. i have used flutter local push notification as the following example link(https://blog.logrocket.com/implementing-local-notifications-in-flutter/) working fine but while clicking the notication the page does’t navigate and reload.

I have also created secondscreen(this is navigate page) but in this code selectNotification functionality not working. please check below code and give me a solution.

//notification_service.dart
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'package:timezone/data/latest.dart' as tz;
import 'package:timezone/timezone.dart' as tz;
import 'secondscreen.dart';

import 'main.dart';

class NotificationService {
  //NotificationService a singleton object
  static final NotificationService _notificationService =
      NotificationService._internal();

  factory NotificationService() {
    return _notificationService;
  }

  NotificationService._internal();

  static const channelId = '123';

  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
      FlutterLocalNotificationsPlugin();

  Future<void> init() async {
    final AndroidInitializationSettings initializationSettingsAndroid =
        AndroidInitializationSettings('@mipmap/ic_launcher');

    final IOSInitializationSettings initializationSettingsIOS =
        IOSInitializationSettings(
      requestSoundPermission: false,
      requestBadgePermission: false,
      requestAlertPermission: false,
    );

    final InitializationSettings initializationSettings =
        InitializationSettings(
            android: initializationSettingsAndroid,
            iOS: initializationSettingsIOS,
            macOS: null);

    tz.initializeTimeZones();

    await flutterLocalNotificationsPlugin.initialize(initializationSettings,
        onSelectNotification: selectNotification);
  }

  AndroidNotificationDetails _androidNotificationDetails =
      AndroidNotificationDetails(
    'channel ID',
    'channel name',
    'channel description',
    playSound: true,
    priority: Priority.high,
    importance: Importance.high,
  );

  Future<void> showNotifications() async {
    await flutterLocalNotificationsPlugin.show(
      0,
      "Notification sundar",
      "This is the Notification Body!",
      NotificationDetails(android: _androidNotificationDetails),
    );
  }

  Future<void> scheduleNotifications() async {
    await flutterLocalNotificationsPlugin.zonedSchedule(
        0,
        "Notification Title",
        "This is the Notification Body!",
        tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
        NotificationDetails(android: _androidNotificationDetails),
        androidAllowWhileIdle: true,
        uiLocalNotificationDateInterpretation:
            UILocalNotificationDateInterpretation.absoluteTime);
  }

  Future<void> cancelNotifications(int id) async {
    await flutterLocalNotificationsPlugin.cancel(id);
  }

  Future<void> cancelAllNotifications() async {
    await flutterLocalNotificationsPlugin.cancelAll();
  }
}

Future selectNotification(String payload) async {
  //handle your logic here
  print('String');
  if (payload != null) {
    print('sundar');
    BuildContext context;
    Navigator.push(
      context,
      MaterialPageRoute<void>(builder: (context) => SecondScreen()),
    );
  }
}

what is callback function?

  1. could you please explain code (fastseries,cb)
  2. how to use fastseries
  3. I dont understatnd cb ,
    what is promisify

const { readFile } = require('fs')
const series = require('fastseries')()
const files = Array.from(Array(3)).fill(__filename)

const print = (err, data) => {
  if (err) {
    console.error(err)
    return
  }
  console.log(Buffer.concat(data).toString())
}

 const readers = files.map((file) => {
  return (_, cb) => {
    readFile(file, (err, contents) => {
      if (err) cb(err)
      else cb(null, contents)
    })
  }
})

series(null, readers, null, print)

Prepending text to list items without class or id tags

I’m working with the Docsify.js markdown parser framework and it automatically creates a sidebar from the headings in a document (unless you manually create a sidebar).

I have some CSS that numbers list elements, but want to convert it to JS as there are rendering issues when classes are added as the page scrolls (ie. adding .active).

Originally I was trialling using this snippet but it doesn’t output it as an auto incrementing hierarchical number system:

var li = document.getElementsByTagName( 'li' );
for( var i = 0; i < li.length; i++ ) {
  var prefix = '1.';
  li[i].innerHTML = prefix + ' Title ' + i;
  prefix++;
}

The sidebar that is generated is in the following format:

<aside class="sidebar">
  <div class="sidebar-nav">
    <ul>
      <li>Title 1</li>
      <ul>
        <li>Title 2</li>
        <ul>
          <li>Title 3</li>
          <ul>
            <li>Title 4</li>
            <ul>
              <li>Title 5</li>
              <ul>
                <li>Title 6</li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
      <li>Title 1</li>
      <ul>
        <li>Title 2</li>
        <ul>
          <li>Title 3</li>
          <ul>
            <li>Title 4</li>
            <ul>
              <li>Title 5</li>
              <ul>
                <li>Title 6</li>
              </ul>
            </ul>
          </ul>
        </ul>
      </ul>
    </ul>
  </div>
</aside>

I understand the HTML structure isn’t valid with <ul> being a descendant of an <ul> but this is the code that is outputted and I have no control over it.

However, I want to be able to number the headings with sections and sub-sections:

1. Title 1
 1.1. Title 2
  1.1.1. Title 3
   1.1.1.1. Title 4
    1.1.1.1.1. Title 5
     1.1.1.1.1.1. Title 6
2. Title 7
 2.1. Title 8
  2.1.1. Title 9
   2.1.1.1. Title 0
    2.1.1.1.1. Title 1
     2.1.1.1.1.1. Title 2

I’m struggling to find a way to be able to target the first <li> (or the H1), and then being able to access the next <ul> via .nextElementSibling to continue the loop and prepend the numbering.

As far as I have gotten to at the moment is: document.querySelectorAll( 'div.sidebar-nav > ul' ) and its not much to go on!

I think I’m really out of my depth for javascript here, and was hoping that I’d be able to get some help on being able to loop through the <li> and ` elements to prepend the numbers.

I want to keep the position of ADD TO CART button right above the bottom of of grid . But its going down when the name of the book exceeds to 2 rows

Screen shot of my grid items of one rowI want to keep the position of ADD TO CART button right above the bottom of of grid . But its going down when the name of the book exceeds to 2 rows. please resolve the issue even if the name of one item is larger than the other item’s names in the same row but the button should remain 5 to 10px above the grid item bottom. Thank You,i tried bottom:0; but it also did not work…

    .items-container {
        display: grid;
        grid-template-columns: repeat(auto-fit,minmax(20rem, 1fr));
     
    }

    .item-box {
        margin: 0 0 20px 10px;
        padding: 0 0 10px 0;
        height: auto;
        background-color: #E6E0DE;
        align-items: flex-end;
        box-shadow: 2px 2px 12px rgba(47,47,47,0.40);
        height:95%;
    }

Type ‘{ label: string; }’ is not assignable to type ‘IntrinsicAttributes & { children?: ReactNode; }’

I am using the Fluent UI, imported the Toggle component and got a UI Toggle exported:

export const UIToggle: React.FunctionComponent = () => {
  return (
    <Stack tokens={stackTokens}>
      <Toggle label="Enabled and checked" defaultChecked onText="On" offText="Off" />
    </Stack>
  );
};

but when I want to use it and update the ‘label’ attribute:

<UIToggle label = "Turn on"></UIToggle>

here is the error:

Type '{ label: string; }' is not assignable to type 'IntrinsicAttributes & { children?: ReactNode; }'.
  Property 'label' does not exist on type 'IntrinsicAttributes & { children?: ReactNode; }'

Can anyone explain why this error appears and how can I solve it?

how do i dynamically load content into an iframe

I have some code that should dynamically load an iframe. The issue is i have a function that should make it cascade to the next id appended to the iframe. I need someone to help pinpont the issue with my code.

    const $iframe = $("#content-frame");
                $($iframe).attr('src', cath);

         var cath = 'https://exanple.com' + myIds[i]+ '/embed/dynamic?';

                console.log(cath);


    const myIds=['1_aq4jiqb','1_4u0ocu4u'];
function switchId() {
for (let i = 0; i < myIds.length; i++) {
cath = 'https://www.exanple.com' + myIds[i]+ '/embed/dynamic?';

}
}
setInterval(function(){ switchId() }, 3000);
 
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>

        <iframe id="content-frame" src="" width="400px" height="400px"></iframe>

How to stop React with HTML5 video element triggering multiple HTTP requests (without React it does one)

When I have a simple HTML page with a <video> tag and you watch network requests in Chrome DevTools or similar, it does a single HTTP request. The video clip is only a few seconds long. Nice and clean!

When I use the same <video> tag markup in React to update the video source URL, it usually triggers 3 HTTP requests. The video works, but it’s no longer a single HTTP request. Its using ranges and so on.

I assume the way the DOM is updated changes the way the <video> element behaves.

My problem is in a complex application I am getting the occasional ‘cancel’ of a HTTP request to the image URL, and then some timing issue seems to sneak in and it can have multiple HTTP requests to the video URL in parallel. This is legal to do, but unfortunately triggers a Windows Chrome bug that results in error messages and the video does not play.

Is there a way to update the DOM using React to not trigger multiple HTTP requests? I was guessing React is incrementally building up the DOM element one attribute at a time, causing the player to pause and restart as it detects attribute changes that might change how the video is rendered. I was wondering if there was a funky way to update the DOM so <video> tags work more reliably (without the multiple HTTP requests for the video element).

reference error text is not defined ejs

So i am making something for fun and i am new to express.js and ejs i made a minecraft server status checker and i want to display the result in <%=text%> from express.js but i am getting this error

ReferenceError: C:UsersUwUOneDriveDesktopUwU webWeb DevelopmentFirebones-Siteviewsindex.ejs:110
    108|         <input type="submit" value="Submit" /> 

    109|     </form> 

 >> 110|     <h1><%= text %></h1>

    111|     </div>

    112|   </body>

    113|   <script src="js/effect.js"></script>


text is not defined
 

my index.ejs

 <form action="/" method="GET"> 
        <input type="text" name="uwu" required /> 
        <input type="submit" value="Submit" /> 
    </form> 
    <h1><%= text %></h1>

express (main.js)

//Imports
const express = require("express");
const res = require("express/lib/response");
const app = express();
const port = 3000;
const path = require("path");
const util = require('minecraft-server-util')
app.use(express.static("public"));
app.use("/css", express.static(__dirname + "public/css"));
app.use("/js", express.static(__dirname + "public/js"));
app.use("/img", express.static(__dirname + "public/img"));
app.set("views", "./views");
app.set("view engine", "ejs");   
app.get("/", (req, res) => {
  res.render("index");
  var input = req.query.uwu;
  util.status(input)
  .then((response) => {
    var players = response.players.online;
    var maxplayers = response.players.max;    
    res.render("index", {text: players} )
  })    
});