Importing vue component into my page Uncaught Exception

I have a page which loads the following JS files

  • Vue.js
  • app.js

The app.js file is compiled using webpack, this includes a NPM component from @chenfengyuan/vue-countdown.

I am trying to display a vue.js countdown component on my page using the following code on my page:

<div class="container" id="app">
    <vue-countdown :time="2 * 24 * 60 * 60 * 1000" v-slot="{ days, hours, minutes, seconds }">
        Time Remaining:@{{ days }} days, @{{ hours }} hours, @{{ minutes }} minutes, @{{ seconds }} seconds.
    </vue-countdown>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="js/app.js"></script>
<script src="https://js.pusher.com/7.0/pusher.min.js"></script>
<script>
    import VueCountdown from '@chenfengyuan/vue-countdown';

    // Vue application
    const app = new Vue({
        el: '#app',
        data: {
            messages: [],
        },
    });
    app.component(VueCountdown.name, VueCountdown);

</script>

When I run this I get a JS error saying:

Uncaught SyntaxError: Cannot use import statement outside a module

Can someone explain what I am doing wrong and how I can correctly import this?

Jquery on client side with nodejs server

I use nodejs (in a docker-compose container, not sure if that is relevant) to set up a local web app. I would like to use jquery on the client-side to load an HTML file into a div. Unfortunately, it is not working. The initial index.html and the new.html are in the same folder (/frontend/). What am I missing?

Nodejs app:


var app = express();

// home route returns rendered html content
app.get("/", (req, res) => {
  res.sendFile(__dirname + "/frontend/index.html");
});

app.listen(3000, function(){
    console.log('Example app listening on port 3000!');
});

index.html:

<!DOCTYPE html>
<html>
    <head>
        <script src="https://code.jquery.com/jquery-3.6.0.min.js"
            integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
            crossorigin="anonymous">
        </script>
        
        <script type="text/javascript">
            $(document).ready(function(){
                $("#imported").load("new.html");
            });
        </script>
    </head>
    <body>
        <div> This is content of the index HTML and below is the imported HTML:</div>
        
        <div id="imported"></div>
    </body>
</html>

Lastly the HTML I want to import new.html:

<HTML>
  <head>
  </head>
  <body>
    <p>This is demo text.<p>
  </body>
</html>

How to extract a JSON value from a node.js “request-promise” https query? The request-promise syntax itself appears problematic

I’m running my javascript code with node.js and am using the request-promise library to generate https requests which return a json blob. So far, I’ve managed to send the request correctly–and I do receive the desired json object in the response, but I’m only seeing the keys, not the values. I want to extract the value for a key called “call_count”. The problem I’m facing is the peculiar structure of the request-promise syntax, which appears to be preventing me from doing what I want to do.

Here’s what the JSON response looks like when I run my query in Postman:

{
  "metric_data": {
    "from": "2021-12-12T23:56:12+00:00",
    "to": "2021-12-13T00:26:12+00:00",
    "metrics_not_found": [],
    "metrics_found": [
        "Mobile/Crash/All"
    ],
    "metrics": [
        {
            "name": "Mobile/Crash/All",
            "timeslices": [
                {
                    "from": "2021-12-12T23:53:00+00:00",
                    "to": "2021-12-13T00:23:00+00:00",
                    "values": {
                        "call_count": 0
                    }
                }
            ]
        }
    ]
  }
}

And here’s my code that generates the request:

const rp = require ('request-promise');

let options = {
  method: 'GET',
  uri: 'https://api.crashCatcher.com/v2/mobile_applications/myAppID/metrics/data.json?names=Mobile/Crash/All&values[]=call_count&summarize=true',
  headers: {
    'User-Agent': 'request-promise',
    'X-Api-Key': 'MY API key goes here'
  },
  json: true // Automatically parses the JSON string in the response
};

rp(options).then(body => console.log(body)).catch(err => console.log(err.name, err.statusCode));

Currently, when I run this code, here’s what I’m getting back:

{ metric_data: 
   { from: '2021-12-13T00:22:04+00:00',
     to: '2021-12-13T00:52:04+00:00',
     metrics_not_found: [],
     metrics_found: [ 'Mobile/Crash/All' ],
     metrics: [ [Object] ] } }

Now, I know I’m getting a JSON object back, and I know I need to do something like:

var myJson = JSON.parse(*body*);

And then something like:

console.log(myJson.metric_data.metrics[0].timeslices[0].values.call_count);

But when using the request-promise syntax, I don’t know how to correctly assign what’s coming back in my response body to a variable that I can then JSON.parse and extract the needed call_count value from.

Node JS – Check if string is a directory

How to check if a string is a directory? I tried casting and using .isDirectory(), not working for me.
Also tried something like this:

let dirs = input.filter(dir => fs.openSync(dir));

but, of course, i get an error when I pass common string. I tried wrapping it into try-catch, didn’t work.

How to export three database tables into one single sheet using datatables?

The website is in Php. I am using datatables.net to export my database table. But, it works fine for one table. But, I have three tables on a web page. How can I export all those three tables into one sheet? Please help.

Script:

<script>
$(document).ready(function() {
    $('#table1').DataTable( {
        dom: 'Bfrtip',
        buttons: [
            'copy', 'csv', 'excel', 'pdf', 'print'
        ]
    } );
} );


</script>

Should I getElementById on button click or on page load? [closed]

Pretty much what the title states, I am debating without much experience if I should getElementId on click or as a global var when the page loads.

So, it’s either this:

var cp1 = document.getElementById('cp1');
var olp = document.getElementById('olp');

ob.addEventListener("click", func_ob);
function func_ob() {
  cp1.classList.add('hidden');
  olp.classList.remove('hidden');
}

Or this:

ob.addEventListener("click", func_ob);

function func_ob (element1, element2) {
  document.getElementById(element1).add('hidden');
  document.getElementById(element2).remove('hidden');
}

If I had to make a guess, I would say this is loading time vs run time? I’m not sure, I could really use someone more experienced to break it down for me a bit.

Thanks in advance!

How to update code to have Error-First callback in Nodejs?

This Code is for a simple Traffic Light, now when running it on the Beaglebone black I receive the warning:”warning: single argument callbacks will be deprecated.please use node-style error-first callbacks: callback(err,response)”. I am unsure of how do do what its asking in my code any help would be appreciated.

var b = require('bonescript');

var red = "p8_13";
var yellow = "p8_15";
var green = "P8_17";
var inputPin = "P8_10";

var switchstatus =0;

b.pinMode(red,b.OUTPUT);
b.pinMode(yellow,b.OUTPUT);
b.pinMode(green,b.OUTPUT);
b.pinMode(inputPin,b.OUTPUT);

var on = b.HIGH;
var off = b.LOW;

setInterval(check,200);

function check(){
    b.digitalRead(inputPin, checkButton);
    }

function checkButton(x){
    if (x.value == 1){
        switchstatus++;
        switch (switchstatus){
            case 1: setTimeout(function
              (){b.digitalWrite(red,on);
                 b.digitalWrite(yellow,off);
                 b.digitslWrite(green,off);},500);
            break;
        case 2: setTimeout (function
              (){b.digitalWrite(yellow,on);},500);
             break;
        case 3: setTimeout (function
              (){b.digitalWrite(red,off);
            b.digitalWrite(green,on);},500);
             break;
        case 4: setTimeout (function
              (){b.digitalWrite(yellow,on)
                 b.digitalWrite(green, on);},500);
             break;
            default: swtchstatus = 0;
            break;
        }
        }
        else if (switchstatus >=5){
            switchstatus = 0;
            callback(err,response);
            }
        }

How to change a className of a particular element based off it’s child input value and input dataset comparison?

It’s my first time posting – hello everyone!

I’m making an app that’s going to help me memorize geographical data.

I have a map with markers on it, when I click on any of these markers a popup appears in which I have an input. I’m comparing the input value with input dataset to see if my answer was correct or not. The thing is, I would also like to change the color of the marker (ImageOverlay) to green as soon as my answer is correct and red if it’s wrong (as soon as any value appears).

The main problem I have is that those markers are mapped from an object which is fetched from firebase, meaning that every single input has to change the color of the corresponding marker and that marker only.

I hope I explained it clearly. Thank you so much in advance!

displayPins that maps data from a firebase doc:

 const displayPins = doc.map((d) => {
return (
  <ImageOverlay
    className="img-overlay"
    key={d.id}
    bounds={[
      [d.latitude - 2, d.longitude - 2],
      [d.latitude + 2, d.longitude + 2],
    ]}
    interactive={true}
    url={`./${d.shape}`}
  >
    <Popup>
      <input type="text" data-tag={d.name} onChange={valueCompare}></input>
      <button
        onClick={() => {
          console.log(test);
        }}
      ></button>
    </Popup>
  </ImageOverlay>
);});

Input’s onChange:

const valueCompare = (e) => {
const data = e.target.dataset.tag;
const value = e.target.value;
if (data != value) {
  console.log("WRONG");
} else {
  console.log("CORRECT");
}};

CSS

.img-overlay {
  filter: brightness(0) saturate(100%);
}
.img-overlay-wrong {
  filter: invert(10%) sepia(95%) saturate(7496%) hue-rotate(11deg)
    brightness(97%) contrast(120%);
}
.img-overlay-correct {
  filter: invert(69%) sepia(61%) saturate(4725%) hue-rotate(78deg)
    brightness(112%) contrast(128%);
}

How to stop collide2D from detecting p5.js

I am using the collide2D library in p5.js to detect if my player hits an obstacle. If it does, i wantthe player to have 1 less lives. The problem i’ve run in to is that when i hit an obstacle it keeps removing lives for the whole time i hover over it so i end up with -100 lives when i hover over the whole obstacle.

Code in class Rock(my obstacle):

    isColliding(obj) {
      let hit = collideRectCircle(obj.x - 55, obj.y - 60, 105, 109, this.x, this.y, 130);
      return hit;
    }

code in draw:

  for (let i = 0; i < rocks.length; i++) {
    if (rocks[i].isColliding(unicorn)) {
      lives -= 1
      // if (lives <= 0) {
      //   gameOver();
      // }
    }

Select option change ‘Formation’

I’m building a Football Team Builder with 5 players per team. The idea is to have a select element with the options Formation 1: 1-1-2, Formation 2: 1-2-1, and Formation 3: 2-1-1 (Goalkeepers are not included in the formation).

I build it in a grid with divs of 3×3. See the table as an example:

Attacker 1 Attacker 2 Attacker 3
Midfielder 1 Midfielder 2 Midfielder 3
Defender 1 Defender 2 Defender 3

Now if I select Formation 1: 1-1-2, I only want to display the players according to the selected Formation. That should look like this:

Attacker 1 Attacker 3
Midfielder 2
Defender 2

How can I accomplish this for every Select Option with javascript?

CODE

<label for="formation"> Formation </label>
<select id="formation" name="formation">
  <option value="1"> 1-1-2 </option> <!-- 2 Attackers-->
  <option value="2"> 1-2-1 </option> <!-- 2 Midfielders-->
  <option value="3"> 2-1-1 </option> <!-- 2 Defenders-->
</select>

<div class="attackers">
  <div class="card" id="attacker_1"> Attacker 1 </div>
  <div class="card" id="attacker_2"> Attacker 2 </div>
  <div class="card" id="attacker_3"> Attacker 3 </div>
</div>

<div class="midfielders">
  <div class="card" id="midfielder_1"> Midfielder 1 </div>
  <div class="card" id="midfielder_2"> Midfielder 2 </div>
  <div class="card" id="midfielder_3"> Midfielder 3 </div>
</div>

<div class="defenders">
  <div class="card" id="defender_1"> Defender 1 </div>
  <div class="card" id="defender_2"> Defender 2 </div>
  <div class="card" id="defender_3"> Defender 3 </div>
</div>

Here is my JSFiddle: https://jsfiddle.net/dnf7a9c0/4/

GAPI Export to Google Sheet Invalid Argument Error

I’m trying to export details from out app into a google sheet and am getting an “Invalid argument” error. I’m trying to take the data from the page and also grab users’ birthdays on export. We use firestore as a db.

exportStaff(shift) {
      console.log(shift)
      const exportHeaders = [
        "Day",
        "Event",
        "Position",
        "Start",
        "End",
        "First Name",
        "Last Name",
        "Phone",
        "Email",
        "Confirmed",
        "DOB",
        "Code",
      ];
      const exportItems = [];
      for (var key in this.orderedPlacedUsers2(shift.id)) {

        function myDOB(staff) {
          return fb.usersCollection.doc(staff).get()
          .then(doc => {
            console.log(doc.data().dob)
            return doc.data().dob
          })
        }

        exportItems.push([
          shift.day,
          shift.event,
          shift.position.title,
          shift.startTime,
          shift.endTime,
          this.orderedPlacedUsers2(shift.id)[key].firstName,
          this.orderedPlacedUsers2(shift.id)[key].lastName,
          this.orderedPlacedUsers2(shift.id)[key].phone,
          this.orderedPlacedUsers2(shift.id)[key].email,
          this.orderedPlacedUsers2(shift.id)[key].confirmed,
          myDOB(this.orderedPlacedUsers2(shift.id)[key].userId),
          `=REGEXEXTRACT(H2,"....$")`
        ])
      }
     
      this.$gapi.getGapiClient().then(gapi => {
        const exportService = new ExportService(exportHeaders, Object.values(exportItems), gapi);
        exportService.export();
      });
    },

All of the birthdays are logging correctly to the console, but no values show on the sheet.

Here is a screenshot of the error in the console.

enter image description here

How can I get the birthdays (DOB) to export properly?

How to search for a specific value in an array of objects

I want to make my code render the data when i search for a value, tried it by using for, but it keeps showing unexpected token. Is there any way to do it properly? It may be an easy question but i don’t really know how to make this work.

export default function SelecionaRota() {
    const rota = {
        locais: [
            {
                nome: 'Rio de Janeiro',
                rotas: [
                    {
                        nome: 'RJ-SP',
                        valor: 1200
                    },
                    {
                        nome: 'RJ-BSB',
                        valor: 1400
                    }
                ]
            },
            {
                nome: 'São Paulo',
                rotas: [
                    {
                        nome: 'SP-RJ',
                        valor: 1200
                    },
                    {
                        nome: 'SP-BSB',
                        valor: 1400
                    }
                ]
            }
        ]
    }
    const location = useLocation()
    const { estadoOrigem } = location.state
    return (
        <div>
            <h1>{estadoOrigem}</h1>
            {for (var i = 0;i < rota.locais.length;i++) {
                if (estadoOrigem === rota.locais[i].nome) {
                    rota.locais[i].rotas.map(module => (
                        <>
                            <h1>{module.nome}</h1>
                            <h2>{module.valor}</h2>
                        </>
                    ))
                }
            }}
        </div>
    )
}

Error:

./src/pages/Rota.js
SyntaxError: D:Arquivos1 Estágio Testeaeroporto-testesrcpagesRota.js: Unexpected token (39:13)

  37 |         <div>
  38 |             <h1>{estadoOrigem}</h1>
> 39 |             {for (var i = 0;i < rota.locais.length;i++) {
     |              ^
  40 |                 if (estadoOrigem === rota.locais[i].nome) {
  41 |                     rota.locais[i].rotas.map(module => (
  42 |                         <>

How to use http-proxy with StompJS?

I have a Stomp client to do websocket communication with. To avoid hardcoding the URL to the websocket broker server I’d like to use a proxy.

I use http-proxy (especially the NuxtJS module nuxt-proxy) in this case. Here is my configuration for it:

// nuxt.config.js
  proxy: {
    '/websocket': {
      target: 'ws://localhost:1001/dispatcher',
      ws: true
    }
  },

I am using the Stomp client the following way:

// stomp client logic
      this.client = new Client()
      this.client.brokerURL = 'websocket'
      if (!this.debug) {
        this.client.debug = () => {
        }
      }
      this.client.onConnect = (_: IFrame) => {
        connectedCallback()
        console.debug('websocket connection established')
        resolve()
      }
      this.client.onStompError = (frame: IFrame) => {
        console.error('Broker reported error: ' + frame.headers.message)
        console.error('Additional details: ' + frame.body)
      }
      this.client.activate()

When testing the whole I see the following error:

Uncaught (in promise) DOMException: Failed to construct 'WebSocket': The URL 'websocket' is invalid.
    at Client._createWebSocket (webpack-internal:///./node_modules/@stomp/stompjs/esm6/client.js:286:25)
    at Client.eval (webpack-internal:///./node_modules/@stomp/stompjs/esm6/client.js:216:36)
    at Generator.next (<anonymous>)
    at fulfilled (webpack-internal:///./node_modules/@stomp/stompjs/esm6/client.js:9:58)
_createWebSocket @ client.js?453e:281
eval @ client.js?453e:211
fulfilled @ client.js?453e:4
Promise.then (async)
step @ client.js?453e:6
eval @ client.js?453e:7
__awaiter @ client.js?453e:3
_connect @ client.js?453e:183
activate @ client.js?453e:180
eval @ websocket.ts?c9d7:32
_callee$ @ websocket.ts?c9d7:14
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:294
eval @ runtime.js?96cf:119
asyncGeneratorStep @ asyncToGenerator.js?1da1:3
_next @ asyncToGenerator.js?1da1:25
eval @ asyncToGenerator.js?1da1:32
eval @ asyncToGenerator.js?1da1:21
connect @ websocket.ts?c9d7:5
_callee$ @ GameServer.ts?226d:24
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:294
eval @ runtime.js?96cf:119
asyncGeneratorStep @ asyncToGenerator.js?1da1:3
_next @ asyncToGenerator.js?1da1:25
eval @ asyncToGenerator.js?1da1:32
eval @ asyncToGenerator.js?1da1:21
connect @ GameServer.ts?226d:16
create @ BootScene.ts?536d:48
create @ phaser.js?d4ef:100338
loadComplete @ phaser.js?d4ef:100250
emit @ phaser.js?d4ef:1908
loadComplete @ phaser.js?d4ef:196794
fileProcessComplete @ phaser.js?d4ef:196760
onProcessComplete @ phaser.js?d4ef:4961
data.onload @ phaser.js?d4ef:19311
load (async)
onProcess @ phaser.js?d4ef:19307
nextFile @ phaser.js?d4ef:196694
onLoad @ phaser.js?d4ef:4890
load (async)
XHRLoader @ phaser.js?d4ef:122925
load @ phaser.js?d4ef:4855
eval @ phaser.js?d4ef:196648
each @ phaser.js?d4ef:41031
checkLoadQueue @ phaser.js?d4ef:196634
start @ phaser.js?d4ef:196584
bootScene @ phaser.js?d4ef:100227
start @ phaser.js?d4ef:100926
bootQueue @ phaser.js?d4ef:99971
emit @ phaser.js?d4ef:1926
texturesReady @ phaser.js?d4ef:162728
emit @ phaser.js?d4ef:1926
updatePending @ phaser.js?d4ef:102052
emit @ phaser.js?d4ef:1907
image.onload @ phaser.js?d4ef:102182
load (async)
addBase64 @ phaser.js?d4ef:102174
boot @ phaser.js?d4ef:102031
emit @ phaser.js?d4ef:1926
boot @ phaser.js?d4ef:162713
DOMContentLoaded @ phaser.js?d4ef:91974
Game @ phaser.js?d4ef:162673
IonPhaser.initializeGame @ ion-phaser.entry.js?af4d:19
connectedCallback @ ion-phaser.entry.js?af4d:50
safeCall @ index-53dab568.js?8203:233
fireConnectedCallback @ index-53dab568.js?8203:436
initializeComponent @ index-53dab568.js?8203:405
await in initializeComponent (async)
connectedCallback @ index-53dab568.js?8203:475
eval @ index-53dab568.js?8203:539
jmp @ index-53dab568.js?8203:9
connectedCallback @ index-53dab568.js?8203:539
insertBefore @ vue.runtime.esm.js?2b0e:5753
insert @ vue.runtime.esm.js?2b0e:6083
createElm @ vue.runtime.esm.js?2b0e:6002
updateChildren @ vue.runtime.esm.js?2b0e:6260
patchVnode @ vue.runtime.esm.js?2b0e:6363
patch @ vue.runtime.esm.js?2b0e:6526
Vue._update @ vue.runtime.esm.js?2b0e:3963
updateComponent @ vue.runtime.esm.js?2b0e:4075
get @ vue.runtime.esm.js?2b0e:4495
run @ vue.runtime.esm.js?2b0e:4570
flushSchedulerQueue @ vue.runtime.esm.js?2b0e:4326
eval @ vue.runtime.esm.js?2b0e:1989
flushCallbacks @ vue.runtime.esm.js?2b0e:1915
Promise.then (async)
timerFunc @ vue.runtime.esm.js?2b0e:1942
nextTick @ vue.runtime.esm.js?2b0e:1999
queueWatcher @ vue.runtime.esm.js?2b0e:4418
update @ vue.runtime.esm.js?2b0e:4560
notify @ vue.runtime.esm.js?2b0e:730
reactiveSetter @ vue.runtime.esm.js?2b0e:1055
proxySetter @ vue.runtime.esm.js?2b0e:4644
onSuccessfulLogin @ index.vue?0f48:26
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
Vue.$emit @ vue.runtime.esm.js?2b0e:3903
_callee$ @ login.vue?ef3c:42
tryCatch @ runtime.js?96cf:63
invoke @ runtime.js?96cf:294
eval @ runtime.js?96cf:119
asyncGeneratorStep @ asyncToGenerator.js?1da1:3
_next @ asyncToGenerator.js?1da1:25
Promise.then (async)
asyncGeneratorStep @ asyncToGenerator.js?1da1:13
_next @ asyncToGenerator.js?1da1:25
eval @ asyncToGenerator.js?1da1:32
eval @ asyncToGenerator.js?1da1:21
login @ login.vue?ef3c:34
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
Vue.$emit @ vue.runtime.esm.js?2b0e:3903
submit @ vuetify.js?ce5b:16249
invokeWithErrorHandling @ vue.runtime.esm.js?2b0e:1863
invoker @ vue.runtime.esm.js?2b0e:2188
original._wrapper @ vue.runtime.esm.js?2b0e:6961
Show 5 more frames

I understand the error however I have no idea how I can use a proxy and the Stomp Client at the same time. I can’t use the ws:// protocol in the Stomp client because I would not trigger the proxy that way (at least that’s what I think)

Any ideas?

VS Code & TypeScript hover over a type

I have been using typescript in vs code and I pretty new to typescript. when I hover an Express type, I get a lot of stuff in a pop up. I really don’t understand where it is coming from. I tried to trace it back, but I am guessing is a built in method in the packages… does anyone know what these are?

import GetServerSideProps

enter image description here