How would I push multiple images into an Array using sessionStorage?

I need to push new images into an array when I regenerate a new image using sessionStorage. Moreover, at the moment I can only output one image at a time to the screen.

My codePen: https://codepen.io/aaron_1986/pen/WNKNJGa


 /*------- API -------*/
      function get_image() {
          let url = `https://api.unsplash.com/photos/random/?client_id=`;
          let imageElement = document.querySelector('.image');

      fetch(url)
         .then(function(response){
          return response.json();
    })

      .then(function(jsonData){
          imageElement.src = jsonData.urls.regular;
    })

    }    
 /*------- OUTPUT SESSION -------*/
      const _SaveData = () => {
         let img = document.querySelector('.image');
         let pic = img.src;
         sessionStorage.setItem('.image', pic);
         document.querySelector('.image2').src = pic;
    }


As above I can only show one image at a time; I know I need to use the push method but I don’t know how.

Failed to load module script: Expected a JavaScript module script but the server responded with a MIME type of “text/html”

I need help for this error, I saw that I’m the only one having this error but I can solved it. Here is my code :
I try to see the status of servers with NODE-PING, and this error appears.

Any idea ?
tk

import ping from '../../../ping';
var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
console.log(hosts);
hosts.forEach(function(host){
    ping.sys.probe(host, function(isAlive){
        var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
        console.log(msg);
     });
 });

Variable is empty ¿why?

I’m learning Javascript, and I have no idea why my variable is always empty even though the call is correct.

let jsonurl = "http://jsonplaceholder.typicode.com/photos";

let request = new XMLHttpRequest();

let myjson;

function reqHandler() {
    if (this.readyState === 4 && this.status === 200) {
        myjson = this.responseText;
        // console.log(this.responseText); // <= This works ok
    }

    return myjson;
}

request.onload = reqHandler;

request.open("GET", jsonurl, true);

request.send();

console.log(myjson); // empty... why??

Thank you!

I am getting unknown file extension error while importing a js file in app.js, using type: module in package.json

I am getting an error while calling a file from routes folder in the main server file.

app.js(main server file code)

import express from "express"
import cors from "cors"
import mysql from "mysql"
const app = express()
import bcrypt from "bcrypt"
import session from "express-session"
import passport from "passport"
import passportLocalMySql from "passport-local-mysql"

app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: true }))

const db = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: '25432900@Meet',
    database: 'quizdb'
})

app.post("/register", cors(), (req, res) => {
    console.log("In server", req.body)
    let userName = req.body.userName
    let userEmail = req.body.userEmail
    const sqlInsert = "INSERT INTO user(user_name, user_email) VALUES (?,?)"
    // const sqlRead = "SELECT * from user"
    const queryResult = db.query(sqlInsert, [userName, userEmail], (err, result) => {
        if (err) {
            console.log("There was some error: ", err)
        } else {
            console.log("Successful")
            res.json(result)
        }
    })
})

import router from "./routes/login"
console.log("Meeet")
app.post("/login", async (req, res) => {
    let userName = req.body.userName
    let userPassword = req.body.password
    const checkQuery = 'SELECT * FROM user WHERE user_id=? AND user_password=?'
    const queryResult = db.query(checkQuery, [userName, userPassword], (err, result) => {
        if (err) {
            console.log("There was some error: ", err)
        } else {
            console.log("Successful")
            res.json(result)
        }
    })
})

app.listen('5000', () => {
    console.log("Listening on port no. 5000")
})

login.js file(the file which is being imported)

const express = require("express")
const router = express.Router()

router.post("/login", async (req, res) => {
    console.log("Meets")
    let userName = req.body.userName
    let userPassword = req.body.password
    const checkQuery = 'SELECT * FROM user WHERE user_id=? AND user_password=?'
    const queryResult = db.query(checkQuery, [userName, userPassword], (err, result) => {
        if (err) {
            console.log("There was some error: ", err)
        } else {
            console.log("Successful")
            res.json(result)
        }
    })
})

module.exports = router

package.json file

{
  "name": "app",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "type": "module",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "node app",
    "nodemon": "nodemon app"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "bcrypt": "^5.1.0",
    "cors": "^2.8.5",
    "express": "^4.18.2",
    "express-session": "^1.17.3",
    "mysql": "^2.18.1",
    "passport": "^0.6.0",
    "passport-local": "^1.0.0",
    "passport-local-mysql": "^5.0.10",
    "sequelize": "^6.26.0",
    "sequelize-cli": "^6.5.2"
  },
  "devDependencies": {
    "nodemon": "^2.0.20"
  }
}

file structure:

  1. app.js, package.json inside main folder
  2. login.js inside router folder inside main folder

I am trying to use esversion 6 but it is throwing an error

Error:

`TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension "" for M:reactquiz-appserverrouteslogin. Loading extensionless files is not supported inside of "type":"module" package.json contexts. The package.json file M:reactquiz-appserverpackage.json caused this "type":"module" context. Try changing M:reactquiz-appserverrouteslogin to have a file extension. Note the "bin" field of package.json can point to a file with an extension, for example {"type":"module","bin":{"login":".routeslogin.js"}}
    at new NodeError (node:internal/errors:393:5)
    at Object.getFileProtocolModuleFormat [as file:] (node:internal/modules/esm/get_format:80:11)
    at defaultGetFormat (node:internal/modules/esm/get_format:122:38)
    at defaultLoad (node:internal/modules/esm/load:81:20)
    at nextLoad (node:internal/modules/esm/loader:164:28)
    at ESMLoader.load (node:internal/modules/esm/loader:603:26)
    at ESMLoader.moduleProvider (node:internal/modules/esm/loader:459:22)
    at new ModuleJob (node:internal/modules/esm/module_job:63:26)
    at #createModuleJob (node:internal/modules/esm/loader:478:17)
    at ESMLoader.getModuleJob (node:internal/modules/esm/loader:436:34) {
  code: 'ERR_UNKNOWN_FILE_EXTENSION'
}

Node.js v18.8.0`

Javascript window,print() prints 400+ blank pages on Chrome, on Firefox only prints one, on Edge it works correctly

I’m currently working on an Angular project with ChartJs, which uses canvas elements. When I want to print the charts with window.print() the outcomes are wildly different. In Firefox it wont create new page for the element that don’t fit on the first, and in Chrome it adds 440 blank pages to the document. No clue what’s going on, but I’d like a uniform outcome, with the correct number of pages (if possible).
Thanks in advance!

I’ve been tinkering with the css, but I’ve got a feeling that it’s a js side problem. I’ve also tried ngx print, but it couldn’t display the canvas elements without converting them to images.

using google signup forms using form action, how to catch error in javascript

I have a form like this that submits an email address to a 3rd party provider like this.

<form action="https://gmail.us11.list-manage.com/subscribe/post?u=XXXXXX" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank" novalidate>
    <div id="mc_embed_signup_scroll" style="display: flex;flex-direction: row;">
        <div class="mc-field-group">
            <input type="email" value="" name="EMAIL" class="required email" id="mce-EMAIL">
            <span id="mce-EMAIL-HELPERTEXT" class="helper_text"></span>

        </div>
        <div style="position: absolute; left: -5000px;" aria-hidden="true"><input type="text" name="b_fb16c0b54b243c41cf0ba431c_6cbe3da72c" tabindex="-1" value=""></div>
        <div class="optionalParent">
            <div class="clear foot">
                <button type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" class="rehab-btn-secondary">Send</button>
            </div>
        </div>
    </div>
</form>

However, sometimes when user input an invalid email format like say “test@test”, I need to handle the error coming from the external API, right now it just display on the mce-EMAIL-HELPERTEXT but my issue is the error returned by them is kind of long and messes up the formatting and I want to catch the error so I can custom format it on my page.

Any idea how to do it?

React Native (Expo) Send an Email with created PDF

I need some help on how to send an Email with a created PDF via Expo and Nodemailer.

I have my Backend Function for the NodeMailer setup and tested to actually work.

In the Frontend I have tried few different Expo Packages but always had something that would not work for me.

How I want it to work is:

  1. On Button Press open the created PDF
  2. When the user wants he can close the File
  3. In the Background send that opened File via my NodeMailer

What I’ve tried:

 await Print.printAsync({
   html,
   orientation: "portrait",
   printerUrl: this.state.selectedPrinter?.url, 
 })

This creates my File and I can save it as PDF! Now this would actually work for me if I could automatically rename the File. When I press save as PDF it is called “Document” but I need to have it named dynamically. I guess if I could rename it I might be able to pick it somehow and send it (like Expo DocumentPicker or FileSystem maybe).

Second approach is to save the File and then open it:

const { uri } = await Print.printToFileAsync({ html });
console.log('File has been saved to:', uri);

try {

  const cUri = await FileSystem.getContentUriAsync(uri);
             
  await ExpoIntent.startActivityAsync("android.intent.action.VIEW", {
      data: cUri,
      flags: 1,
      type: "application/pdf",
  });
}catch(e){
    console.log(e.message);
}

The Code saves my File and opens it up again. Now here is a URI I can access which looks kinda like this:

file:///data/user/0/host.exp.exponent/cache/ExperienceData/%2540xyyxwyx%252FPXXXX/Print/eb03cc8c-9c29-4d08-aed8-f10eXXX87fe5.pdf

When I try to use that URI and send it via nodemailer it tells me that the file does not exist!

Error Mail: Error: ENOENT: no such file or directory, open 'C:DevProgrammierungrnxxx-Serverfile:datauserhost.exp.exponentcacheExperienceData%2540xxyx%252FxxxPrintcbcff690-d608-4138-a635-93cxxy72a2ed.pdf'

Which makes sense since that file is not available on my PC, its only inside my Emulator. How do I tell Expo the correct URI Link?

So whats important (one of the two):

  1. Renaming the File and save it under the correct name
  2. using the correct URI

I also had some approaches renaming the File using Expo Filesystem and Expo Sharing but not really the way I wanted it. If anyone could give some advice on how to achieve this would be great, or even different approaches with Expo DocumentPicker for example.

hls.js in react application

Currently, I’m using hls js in my react application, but I’m having trouble getting levels and qualities from the manifest
Actually, Hls.Events.MANIFEST_PARSED does not fire in Android browsers. On PC, it works fine; however, this issue only occurs in Android browsers. this is part of my code .

const newHls = new Hls({
                enableWorker: false,
                ...hlsConfig,
            });

newHls.once(Hls.Events.MANIFEST_PARSED, (event, data) => {
                if (autoPlay) {
                    setIsPlaying(true)
                    playerRef?.current
                        ?.play()
                        .catch((e: any) => {
                                console.log(e)
                                setIsPlaying(false)
                            }
                     
            });

How to get data from script tag

I’m trying to create a javascript function to get my website script tag data in my admin.

In my main page i have this script tag as below

<script>
    window._global = {
        'login': true
    };

    window._custom = {
        'userId': 1,
        'name': 'Joe Bond'
    };
</script>

And in my admin i’m trying to get the script variable to be used in admin. But not sure how to do so.

I have tried document.scripts[1].innerHTML but i’m getting as string. How can i convert it into object ?

How to add JSX elements to a page

I have a function that should add a div 6 times to a page, but it only adds one. What to do?
I have styles

      function Six(){ 
        for(let i=0;i<6;i++){
            return(<div className='blocksix all'/>)
        }
      }
return(
    <div className="App">
        <Six />
    </div>
)

I tried to write a loop in return but errors appear

ES5 : mocha and qunit.js

I have qunits written using QUnit.js, now I am trying to integrate Qunit.js with mocha so that I can execute both unittests with single mocha command.

I have installed qunit and mocha using npm.

➜ npm ls

├── [email protected]
├── [email protected]
├── [email protected]
├── [email protected]
└── [email protected]

And when I tried to run the mocha command

> mocha --require qunit --package ./package.json ./*.js

ReferenceError: QUnit is not defined

I am using ES5 JS Syntax, so I can’t add lines like require in my .js files. Is there any way we can achieve this?

Audio Editor with React and ASP

I am in need of a nuget package/library which offers the functionalities to edit audio files (such as changing pitch/tempo/trimming audio) on a website that will be made with React.

Looking forward to your suggestions.

I didn’t have much luck with finding one.

How to add table using html? [closed]

I want to create table using HTML as i am not understanding how to create it now i want a code by which i can create a table in my webpage and store the data in it and how i can adjust the size of the table.

`<!DOCTYPE html>
<html>`

`<head>
</head>
`
`<body>

  <table>
    <tr>
      <th colspan="2">Company</th>
      <th>Name</th>
    </tr>`
   ` <tr>
      <th rowspan="2">
        </td>
      <th>
        </td>
      <th>
        </td>
    </tr>
    <tr>

      <th>
        </td>
    </tr>
  </table>
</body>

</html>