I created a REST Api using nodejs and mongodb and i wanted to test it in postman but while doing so I am getting a CORS error

'use strict';

const app          = require('koa')();
const jwt          = require('koa-jwt');
const bodyParser   = require('koa-bodyparser');
const send         = require('koa-send');
const serve        = require('koa-static');
const jsonwebtoken = require('jsonwebtoken');
const error        = require('./middleware/error-middleware.js');
const router       = require('koa-router')();

// do not use this secret for production
const secret = 'supersecret';

app.use(error());
app.use(bodyParser());
app.use(serve('dist'));
app.use(jwt({ secret }).unless({
    path: [/^(?!/api/)/]
}));

// for example use, we just check for specific username/password
// in the real world, we would check a database and check hashed password
router.post('/auth', function* () {
    const username = this.request.body.username;
    const password = this.request.body.password;

    if (username !== 'chuck' && password !== 'norris') {
        this.throw(401, 'Invalid username/password.');
    }

    const user = {
        username,
        email: '[email protected]',
        firstName: 'Chuck',
        lastName: 'Norris',
        roles: ['admin']
    };

    const token = jsonwebtoken.sign(user, secret, {
        issuer: 'localhost',
        audience: 'someaudience',
        expiresIn: '1d'
    });

    this.body = { token };
});

app.use(router.routes());

app.use(function* () {
    yield send(this, '/dist/index.html');
});

app.on('error', err => console.log(err));

app.listen(3000, () => console.log('example running on port 3000'))

;
//how to solve this error
if I run a server with the port 80, and I try to use XMLHttpRequest I am getting this error: Error: listen EADDRINUSE Why is it problem for NodeJS, if I want to do a request, while I run a server on the port 80? For the webbrowsers it is not a problem: I can surf on the internet, …

Creating a dynamic monolithic HTML page on Github Personal Pages?

I would like to create a journal / game (pixel engine; paint-like).

I would like the database to be on the HTML page.

I would like the page to dynamically update client-side.

The goal here is to have a single index.html file that does it all; accessible to all.

dmontrael.github.io

I can barely capture an input from a textbox and display it. LOL SOS 911!!! ty

I am just statically adding things when i commit the newly updated HTML.

Maybe some links and resources would be nice. All the best. -D.Montrael

How can I access a dictionary in its own class/context to define a method?

A toned-down example is this class, inheriting from PublishableAction (to provide the static .viewController() function as well as other methods which is used where the // ... is):

class Action extends PublishableAction {

  static actionSelector = {
    buttonCommit: Symbol()
  };

  // This part still works as intended, accessing 'Action':
  static buttonSession = Action.viewController({
    perform: Action.actionSelector.buttonCommit
  });

  // ... but here's the issue:
  // ReferenceError: Cannot access 'Action' before initialization
  [Action.actionSelector.buttomCommit]() {
    // ...
  }
}

I have already tried using [this.actionSelector.buttonCommit]() and [this.constructor.actionSelector.buttonCommit](), both not having any effect on the outcome.

How can I fix the ReferenceError without having to move Action.actionSelector to the global scope?

Show menu onclick on multiple posts with same classes

So I made a posting system with PHP and it’s finally working, though, I have a problem. I coded a javascript that opens the post menu, but it won’t open at all. If I were to use the getElementById function, only the first post will be selected so the other posts’ menu won’t open, so I tried using the getElementsByClassName, but now the menu won’t open in any posts.

Here is my code:

let postMenu = document.getElementsByClassName("post-Menu");
let morebtn = document.getElementsByClassName("morebtn");

morebtn.onclick = function() {
    postMenu.classList.toggle("postmenShow");
}
<div class="postmenu">
    <div class="morebtn">
        <svg viewBox="0 0 24 24" aria-hidden="true" class="r-4qtqp9 r-yyyyoo r-1xvli5t r-dnmrzs r-bnwqim r-1plcrui r-lrvibr r-1hdv0qi"><g><circle cx="5" cy="12" r="2"></circle><circle cx="12" cy="12" r="2"></circle><circle cx="19" cy="12" r="2"></circle></g></svg>
    </div>
    <div id="to-open" class="post-Menu">
        <a href="">
            <div class="mlist"><i class="uil uil-trash"></i>&nbsp;&nbsp;Delete</div>
        </a><a href="">
            <div class="mlist"><i class="uil uil-pen"></i>&nbsp;&nbsp;Edit</div>
        </a>
    </div>
</div>

Better way to turn object with named booleans into array with their uppercase keys?

I’m trying to convert the methods part of an Express Router into a one-dimensional array of uppercase string words, so this:

layer.route.methods: { get: true, post: true }

into:

methods: ["GET", "POST"]

This is what I came up with, but isn’t there a more subtle way?

const methods = [];
!layer.route.methods.get || methods.push('GET');
!layer.route.methods.post || methods.push('POST');

when pressing on start button , background color of the browser window is not getting changed

When I press start button the background color of browser window should change . First it should turn to red for 30 seconds then to orange for 5 seconds and then to green for 30 seconds.It should happen atleast once.
Below is HTML file :

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<h1>Traffic Light</h1>
<div>
<button id="btn1">Start</button>
</div>
</body>
<script src="TrafficLightJS.js"></script>
</body>
</html>

Below is Javascript file:

const colors=["red","yellow","green"];
const btn=document.getElementById("btn");
//const color=document.querySelector(".color");
btn.addEventListener("click",function()){
setInterval(function())  {
document.body.style.background=colors[0];
},30000);
setInterval(function())  {
document.body.style.background=colors[1];
},5000);
setInterval((function()) {
document.body.style.background=colors[2];
},30000);

}

Please also tell whether I have to include CSS file or not .If yes,then what will the code in CSS file

Trouble ADDING points to quiz game. It adds 2 instead of 1. JS

Yes, i’ve looked into the stackoverflow recommendations about posts with similar titles and nothing solved my issue. Im new to JS, im trying to make a simple multiple choice quiz. If you get it correct you score a point, if not, u dont get any but the question counter increases, the thing is after the first question everything adds double the value, here’s a quick video showcasing de error: https://gyazo.com/9fbdf63508b2713992935d813f29788e pay attention to the bottom-right corner.

This is a side project and ive been stuck on it for almost 2 weeks now.. no joke. Any help is extremely appreciated, my main language is Spanish so thats the reason of the variables names. Here’s the code:

let pregunta = document.getElementById('preguntafinal');

let puntaje = document.getElementById('puntaje');

let opcion1 = document.getElementById('opcion1');
let opcion2 = document.getElementById('opcion2');
let opcion3 = document.getElementById('opcion3');
let opcion4 = document.getElementById('opcion4');

let puntito1 = document.querySelector('puntito1');


let idPreg = 0;
let respSeleccionada;
let puntosTotales = 0;
let preguntasTotales = 0;

function iterarJuego() {


    pregunta.innerText = arrayPreguntas[idPreg].preg;

    opcion1.innerText = arrayPreguntas[idPreg].opcionuno;
    opcion2.innerText = arrayPreguntas[idPreg].opciondos;
    opcion3.innerText = arrayPreguntas[idPreg].opciontres;
    opcion4.innerText = arrayPreguntas[idPreg].opcioncuatro;;

    elegirRespuesta();


}


function elegirRespuesta(){

    opcion1.addEventListener("click", asd=> {

        respSeleccionada = arrayPreguntas[idPreg].opcionuno;
        funAnalizar(respSeleccionada);

    });

    opcion2.addEventListener("click", asd=> {

        respSeleccionada = arrayPreguntas[idPreg].opciondos;
        funAnalizar(respSeleccionada);

    });

    opcion3.addEventListener("click", asd=> {

        respSeleccionada = arrayPreguntas[idPreg].opciontres;
        funAnalizar(respSeleccionada);
    });

    opcion4.addEventListener("click", asd=> {

        respSeleccionada = arrayPreguntas[idPreg].opcioncuatro;
        funAnalizar(respSeleccionada);

    });

}



function funAnalizar(){

    console.log(respSeleccionada);
    console.log(arrayPreguntas[idPreg].error);

    if (respSeleccionada == arrayPreguntas[idPreg].error) {

        console.log("correcto");
        respCorrecta(respSeleccionada);

    }

    else if (respSeleccionada != arrayPreguntas[idPreg].error) {

        console.log("incorrecto");
        respIncorrecta(respSeleccionada);
    }

}


function respCorrecta(){

        puntosTotales++;
        preguntasTotales++;
        puntaje.innerText = puntosTotales + "/" + preguntasTotales;
        idPreg++;
        iterarJuego(idPreg);
        console.log("ja");
}


function respIncorrecta(){

        preguntasTotales++;
        puntaje.innerText = puntosTotales + "/" + preguntasTotales;
        idPreg++;
        iterarJuego (idPreg); 
        console.log("jant");
}

arrayPreguntas = [ {

        idPreg : 0,
        preg : "Que significa AI en Japonés?",

             opcionuno: 'amor',  
             opciondos: 'carcel', 
             opciontres: 'pizza',   
             opcioncuatro: 'caja', 
             error:'amor'       
            


        } , {

        idPreg: 1,
        preg: "Cual es el hiragana 'ME' ?",

             opcionuno: 'ぬ',  
             opciondos: 'ね', 
             opciontres: 'ぐ',   
             opcioncuatro: 'め',     
             error:'め'  

        } , { 

        idPreg: 2,
        preg: "En hiragana: DESAYUNO , ALMUERZO , CENA ?",

             opcionuno: 'ぬ',  
             opciondos: 'ね', 
             opciontres: 'ぐ',   
             opcioncuatro: 'め',     
             error:'め'

        } , {

        idPreg: 3,
        preg: "Como se dice madre y padre ?",

             opcionuno: 'chichi hana',  
             opciondos: 'hana mitsu', 
             opciontres: 'kirei chichi',   
             opcioncuatro: 'undo chichi',   
             error:'kirei chichi'
        } , {

        idPreg: 4,
        preg: "Que significa きれい ?",

             opcionuno: 'rey y reina',  
             opciondos: 'lindo y linda', 
             opciontres: 'hermoso y hermosa',   
             opcioncuatro: 'salvaje y saldro',  
             error:'lindo y linda'
        }
]




iterarJuego(); 

Thats the .js ..if for some reason the html is needed ill add it with an edit.

Is there a way I can make the input to act like “display: inline-block”?

What I am trying to do is implement a simple inline editing, I’m using a normal div to display the text when the edit state is false, and render an input when the edit state is true.

The problem I’m facing is that the input doesn’t wrap around the text content it’s got, like a div with display: inline-block would. I tried setting the size attribute of the input to be that of the current value’s length, but it’s not wrapping around the content perfectly.

Any ideas how to do it? I guess contentEditable on the span itself, without an input, is an option, but I want to be able to select all the content in the input when it gets the focus.

Here is the code.

import { useState, useRef, useEffect } from "react";

export default function App() {
  const [value, setValue] = useState("test");
  const [active, setActive] = useState(false);
  const ref = useRef();

  useEffect(() => {
    ref.current?.select();
  }, [active]);

  const length = value.split(" ").join("").length;

  return (
    <>
      {!active && <span onClick={() => setActive(true)}>{value}</span>}
      {active && (
        <input
          value={value}
          size={length}
          ref={ref}
          onChange={(e) => setValue(e.target.value)}
          onBlur={() => setActive(false)}
        />
      )}
    </>
  );
}

How to pause setTimeout and then continue it?

https://jsfiddle.net/mhLaj3qy/1/

const changeTimeset = setTimeout(()=>{
    if (is_paused) return;
    bgImage.style.backgroundImage = array[current]
    
    changeBackgroundImages(data, ++current % array.length)
}, a)

function chandgeBackgroundImageOnMouse() {
    samoyed.addEventListener("mouseover", ()=>{
        bgImage.style.backgroundImage = house
        is_paused = true
})
    samoyed.addEventListener("mouseleave", ()=>{
        is_paused = false
    })
}
chandgeBackgroundImageOnMouse()

}

How to pause setTimeout and then continue it? It should be like when it hovered on text – picture stops auto slider, when it mouseout – auto slider is working
Here i tried to do it with it_paused = false/true. But nothing succeeded. What am i doing wrong?

AngularJS/JavaScript – How to chose what array element to display in html table

I have an application that reads an excel file, and displays its contents in an html table.

These elements are in an array called “AgendaItems”.

There are 2 files the user can read, each is formatted with some differences.
Both have 3 columns.

File 1: AgendaItem, LegistarId, Title
File 2: Agenda #, File #, Title

I am able to read the file and populate the array $scope.AgendaItens with the contents of either file, depending what the user selects.

My problem is that before making these modifications to accept a second file with a different format, I used:

<td scope="row">{{ai.AgendaItem}}</td>
<td>{{ai.LegistarID}}</td>

When processing the new file, now the array contains: Agenda #, and File #, which are equivalent to AgendaItem, and LegistarID respectively.

Is there a way to, in the HTML choose which value to display? for example, if array has AgendaItem, display AgendaItem, if array has Agenda #, display Agenda #?

Please let me know if I need to post more details, more code in order for me to be able to get help.

Thank you in advance,
Erasmo

How to implement Silent Printing of images in Node.js or Electron.Js

I’m creating a node application, in which I’m getting Images from the Database and then I’m manipulating its Size using sharp library And loading it into the canvas using Fabric.js, then I’m converting the canvas into base64 png image, now I have got the base64 string of png image, my requirement is I want to print this image using default printer available, but it should be silent printing! by silent I mean it should not popup chromes print preview dialogue box. it should print continuously in the background! I’ve tried node-printer but it doesn’t work, maybe we can only print text files not images with node-printer! Any suggestions are appreciated Thanks!

Fitting a child div inside parent divs fixed size

I have a child div which is a css gird (that is being created by js which will change on users input)that i want to fit 100% according to the parent divs fixed height and width. How do I proceed with this?

var count = 32;
for (var i=0; i<count ; i++){
    const container = document.querySelector('#grid-container');

    const content = document.createElement('div');
    content.classList.add('grid-item');

    container.appendChild(content);
}
.grid-item {
    background-color: rgb(255, 255, 255);
    border: 1px solid rgba(0, 0, 0, 0.8);
    padding: 20px;
}

.grid-container {
    display: grid;
    grid-template-columns: repeat(4, 1fr);
    grid-template-rows: repeat(auto-fill);
    height:100%;
}

.container{
    width: 400px;
    height: 400px;
    border: 15px solid green;
}
<!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>Etch-A-Sketch!</title>
    <link rel="stylesheet" href="styles.css">
    <link rel="stylesheet" href="reset.css">
    <script src="app.js" defer></script>
</head>
<body>

    <div class="container">
      <div class="grid-container" id="grid-container">
    </div>

</body>
</html>

How to solve the Place Students problem shown below?

Question: Place Students

Problem Statement:
There are N consecutive seats in the classroom. Each seat is either
defective or not

In the classroom, there are X boys and Y girls students present. And
you want to place them in such a way that there are no two
consecutive (adjacent) seats where two boys or two girls are sitting
Your task is to find the maximum number of students you can place
Note: You can’t place a student where the seat is defective.

Constraints:

1<=T<=10
1 <=N<= 10^5
0<=X, Y<=10^5

Input Format:
-> The first line of the input contains a single integer T denoting the
number of test cases. The description of T test cases follows

-> The first line of each test case contains three space-separated
integers N, X, and Y.

-> The second line contains a string with length N, consisting of
characters *.” and “#”. The dot means that the corresponding place is
not defective. The hash (“#”) means that the corresponding place is
defective

Output Format:
-> For each test case, print the maximum number of students you can place

Sample Input
7 1 4
.#….#
11 3 10
.#….#.#..
2 1 4

Sample Output
4
8
0

Explanation of Sample:-
Sample case 1: you can put 1 boy and 3 girls in the following way:
“GHGBG#”
Sample case 2: you can put 3 boys and 5 girls in the following way:
“G#GBGB#G#BG”

Here B means boy student, G means girl student.

use handleSeeked() function in videojs

I’m using videojs to play videos on the site and I’m trying to create log on video streams but I have difficulty logging users seeking in videos. I need seek start and end time and it seems that the built in handleSeeked() function in videojs does the job but I can’t get it to work. Does anybody know how to use this function?