Why is Dockerized node.js Server with Vanija JS client not connecting over Socket.io

Git repo

I have an app, composed of:

  1. MySQL server
  2. scraper (node.js)
    • app parse data from website and save it to MySQL.
  3. server (node.js)
    • listening for upcoming connections over socket.io and serving data to the client.
  4. client (Vanilla JS/HTML)

server/controllers/SocketController.js

// Server: http server and socket init
const http = require('http').createServer();
const io = require('socket.io')(http, {
    cors: { origin: "*" }
});

http.listen(3001,() => console.log('Server listening on 3001'));

server/Dockerfile

FROM node:16

WORKDIR /server

COPY /server/package.json .

RUN npm install

COPY /server .

EXPOSE 3001
CMD [ "node", "index.js" ]

web/app.js

// Client listen on localhost:3001
const socket = io('ws://server:3001/');

When working locally everything worked fine, then I decided to make my life miserable and try to dockerize the whole thing (using docker the first time).
First, everything went smooth, made MySQL, scraper, and server up and working just fine.

Then it came to the point I would need to set up Nginx webserver I did so inside docker-compose.yml

docker-compose.yml

version: "3.7"

services:
  mysqldb:
    image: mysql:5.7
    container_name: mysql
    restart: unless-stopped
    env_file:
      - ./.env
    environment:
      MYSQL_DATABASE: ${MYSQL_DATABASE}
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
      MYSQL_PASSWORD: ${MYSQL_ADMIN_PASSWORD}
      MYSQL_USER: ${MYSQL_ADMIN_USERNAME}
    ports:
      - $MYSQL_PORT:$MYSQL_PORT
    volumes:
      - ./db:/docker-entrypoint-initdb.d
    networks:
        - celtra_lottery_network

  scraper:
    restart: unless-stopped
    container_name: scraper
    build:
      context: .
      dockerfile: ./scraper/Dockerfile
    image: scraper
    env_file:
      - ./.env
    ports:
      - $NODE_SCRAPER_PORT:$NODE_SCRAPER_PORT
    volumes:
      - ./scraper:/scraper
      - /scraper/node_modules
    depends_on:
      - mysqldb
    stdin_open: true
    tty: true
    networks:
        - celtra_lottery_network

  server:
    restart: unless-stopped
    container_name: server
    build:
      context: .
      dockerfile: ./server/Dockerfile
    image: server
    env_file:
      - ./.env
    ports:
      - $NODE_SERVER_PORT:$NODE_SERVER_PORT
    volumes:
      - ./server:/server
      - /server/node_modules
    depends_on:
      - mysqldb
    stdin_open: true
    tty: true
    networks:
        - celtra_lottery_network

  client:
    image: nginx
    container_name: client
    ports:
        - 80:80
    volumes:
      - ./web:/usr/share/nginx/html
    networks:
      - celtra_lottery_network
    links:
      - server

volumes:
  db-config: null
  db-data:

networks:
   celtra_lottery_network:
      driver: bridge

When I open Nginx container in the browser, it shows the page but the data is not there. Strangely the console is not showing any error msg.

Already try it:

  • Is the server inside docker running ✔️
  • Is the server port exposed ✔️
  • Change the client connection string to ‘0.0.0.0:3001’ ✔️

I assumed that I would connect to socket the same way I was connecting server and scraper to MySQL so:

  • Host would be the docker-container-name
  • Port would be the EXPOSE 3001 port that the server is listening on.

Question:
Can someone point out the problem in my code would be really grateful for any help.

Why my Asp button doesn’t works even i added Onclick Event inside modal popup?

I have used ASP Button and added OnClick event in it, but while clicking the button it doesn’t works. Kindly help me out to sort out this!

HTML:

<asp:Button ID="Create_project" runat="server" Text="Create Project" OnClick="Create_project_Click"/>

Code Behind:

protected void Create_project_Click(object sender, EventArgs e)
    {
       Response.Write("Sucessfull");
    }

even i couldn’t insert the values to database!

“Note: I am using this button(Create_project) inside the Ajax:modalpopupextender”

How to fix register and login

I’m trying to connect firebase with my vue3 project. I want to build a register and login in my website. I can see the register in firebase web, but when I register a user, route.push is not working to redirect on “/”.

Here is my code:

Register

export default {
  name: "register",
  data: function () {
    return {
      form: {
        email: "",
        password: "",
      },
      error: null,
    };
  },
  methods: {
    register: function (e) {
      const auth = getAuth();
      createUserWithEmailAndPassword(auth, this.form.email, this.form.password)
        .then((userCredential) => {
          userCredential.user
            .updateProfile({
              displayName: this.form.email,
            })
            .then(() => {
              alert("User successfully registered!");
              this.$router.push("/login");
            });
        })
        .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          console.log(errorCode);
          console.log(errorMessage);
        });
      e.preventDefault();
    },
  },
};

Login

export default {
  name: "login",
  data: function () {
    return {
      user: {
        email: "",
        password: "",
      },
      error: null,
    };
  },
  methods: {
    login: function (e) {
      const auth = getAuth();
      signInWithEmailAndPassword(auth, this.user.email, this.user.password)
        .then((userCredential) => {
          userCredential.$router.replace({ name: "Home" }).then(() => {
            this.$router.push("/");
          });
        })
        .catch((error) => {
          const errorCode = error.code;
          const errorMessage = error.message;
          console.log(errorCode);
          console.log(errorMessage);
        });
      e.preventDefault();
    },
  },
};

When u do a register, the website have to redirect you to /. When you log in it has to redirect you to 7 too.

I have a problem with login because it is not working. I can’t log in with an existed user.

Any help?¿

Thanks

SpringBoot RestController with @RequestParam and JQuery $.get()

I want to make my little project and build a Library app with API on Java and UI with ThymeLeaf and JQuery. Here is my controller

@GetMapping(value = "/books-genre")
    public List<BookDto> findBooksByGenre(@RequestParam(name = "genre2") String genre) {
        System.err.println(genre);
        List<Book> books = BookService.findBooksByGenre(genre);
        return bookDtoConverter.booksToDto(books);
    }

Here is my UI in AJAx.

<script>
    function findBooksByGenre () {
        var x = document.getElementById("genre").value;
        console.log(x);
        var param = $.param(genre, x);
        var param2 = {
          genre : x
        };
        $.getJSON('/books-genre/' + $('#genre2').val()).done(function (books2) {
            alert(books2.length);
            books2.forEach(function (book2) {
                coment = book2.comments.length;
                cond = coment != 0 ? coment : 'no comments';
                $('tbody').append(`
                    <tr>
                        <td>${book2.id}</td>
                        <td>${book2.name}</td>
                        <td>${book2.author.name}</td>
                        <td>${book2.genre.name}</td>
                        <td> ${cond}
                        <a href="comments/?bookId=${book2.id}">view</a>
                        </td>
                    </tr>
                `)
            });
        })
    };
</script>


<div class="a">
    <h2>Options</h2>
    <form action="">
        <label for="genre">Choose by genre: </label>
        <input type="text" id="genre"/>
        <input type="submit" onclick="findBooksByGenre()" value="Submit"><br><br>
    </form>
</div>

I want to make a table with these books. But every my call do nothing! As if getJSON does not see my query params at all! I try another functions too, for example just get(/books-genre, {genre2 : drama}).done()...... nothing change. Please Help me say me what I do wrong… Because another controller without query params works well

Hiding spaces with zero values in bar chart with chart.js

I’ve got bar charts with multiple labels and zero data values for some labels.

enter image description here

I need to hide zero-values in chart and draw bars in the middle of current label value. How can i do it?

Here source code:

var chartDebugData = {
    labels: ["2021-11-16", "2021-11-17", "2021-11-18"],
    datasets: [
        {
            label: "Data1",
            backgroundColor: "rgba(161, 198, 76, 0.5)",
            borderColor: "rgba(161, 198, 76)",
            data: [
                66,
                77,
                0,
            ],
            borderWidth: 2,
        },
        {
            label: "Data2",
            backgroundColor: "rgba(107, 228, 46, 0.5)",
            borderColor: "rgba(107, 228, 46)",
            data: [
                55,
                0,
                82,
            ],
            borderWidth: 2,
        },
    ]
}

const canvasEl = document.getElementById("charts");

// Draw graph
new Chart(canvasEl, {
    type: 'bar',
    data: chartDebugData,
    options: {
        barValueSpacing: 5,
    },
});

JSFiddle: https://jsfiddle.net/70n3h1r4/4/

Passing an Arduino Variable to JS

This may be a very simple question for someone out there.

Say I have an int Arduino vairble:

int sensorData = analogRead(sensorPin);

How would I be able to pass that as a JS variable?

client.println("<script> var dat = sensorData </script>"); // this is what I have tried

For more context, I am trying to pass the variable to update a webpage heading; which does work if I pass in a JS variable, but not an Arduino one:

client.println("<h1 id="sensorData"> %SENSORDATA% </h1>");
client.println("document.getElementById("sensorData").innerHTML = dat");

Any help would be greatly appreciated.

Multiple array in a loop (php)

Here I have a loop with ‘i’ as value and I need to create an array of different name for each iteration
how can I do this in php

 $i=0;
while($row3 = mysqli_fetch_assoc($result3))
    {
       
       $edt $i[]=$row3['value'];
        $i++;
    }

Firebase: Error (auth/invalid-email) in Vue

I’m fairly new to Vue (and not too experienced a dev tbh either) and been following this tutorial to create authentication for my app, but since the firebase code used in it is not Firebase v9, it does not work at all for me.
I figured I try to work around figuring it all out and just used the compat libraries, and somewhat updated the code. Now I keep getting mentioned error, and obviously no user creation happens in firebase either.

  <h1>Create an Account</h1>
  <p><input type="text" placeholder="Email" v-model="email" /></p>
  <p><input type="password" placeholder="Password" v-model="password" /></p>
  <p><button @click="register">Submit</button></p>
</template>

<script setup>
  import firebase from 'firebase/compat/app'
  import { getAuth, createUserWithEmailAndPassword } from "firebase/auth";
  import { useRouter } from 'vue-router' // import router

  const email = ''
  const password = ''
  const router = useRouter() // get a reference to our vue router
  const register = () => {

    const auth = getAuth()
    return createUserWithEmailAndPassword(auth, email,password)

      .then((userCredential) => {
        console.log('Successfully registered!');
        router.push('/feed') // redirect to the feed
      })
      .catch(error => {
        console.log(error.code)
        alert(error.message);
      });
  }
</script>

This is my register page which returns the error… I feel dumb for not getting it, can anybody help a noob dev with his basic problems?

Cannot declare the “else” statement in Java script Visual Studio Code?

New to coding and getting errors in basic coding. Following a youtube tutorial for learning but getting the error even after coding the same way as shown in my tutorial video.

var age = prompt ("what is ur age?");

`If ( (age>= 18)   &&   (age<= 35) ); {

var status = “my audience”;
console.log (status);} else {
var status = “not intrested”;
console.log(status);
}`

Upon running the program, the error generated is Unexpected token ‘else’.

Manifest v3 inject script from popup.js

In manifest v2 this code worked and injected the script when button was clicked:

popup.js v2 (works)

document.addEventListener('DOMContentLoaded', function () {
// Get Scan button by ID
var scanButton = document.getElementById('btnScan');

// Define Scan button on click action
scanButton.onclick = function () {
    chrome.tabs.executeScript(null, {
        file: 'Scripts/script.js'
    });
    window.close();
    }
});

Now in manifest v3, chrome.tabs.executeScript is replaced with chrome.scripting.executeScript.

scripting permission is added in manifest.json.

popup.js v3 ()

document.addEventListener('DOMContentLoaded', function () {
// Get Scan button by ID
var scanButton = document.getElementById('btnScan');

// Define Scan button on click action
scanButton.onclick = function () {
    chrome.scripting.executeScript
        (
        {
            target: { tabId: null}, // ???????
            files: ['Scripts/script.js']
        }
        );
    window.close();
    }
});

The problem is that chrome.tabs.executeScript requires tabId value as one of the parameters.
How can I get tabId value in popup.js or convert the manifest v2 version javascript so that it works the same?

Hide two blocks at the same time

I have a method on a page that opens and hides a scrolling block in certain places

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

<head>
  <script>
    var sideMenu, footer, wrapper, nsl;

    document.addEventListener("DOMContentLoaded", init, false);

    function check() {
      var range = document.body.scrollHeight - footer.offsetHeight;
      var position = (nsl.offsetHeight + nsl.getBoundingClientRect().y - wrapper.getBoundingClientRect().y).toFixed(1);

      nsl.innerText =
        'n Range: ' + range +
        'n Position: ' + position;

      if (window.scrollY > 200 && (range > position)) {
        nsl.style.visibility = "visible";
      } else {
        nsl.style.visibility = "hidden";
      }
    };

    function init() {
      sideMenu = document.getElementById('sideMenu');
      footer = document.getElementById('footer');
      wrapper = document.getElementById('wrapper');
      nsl = document.getElementById('navShareLink');

      window.onscroll = check;
      check();
    }
  </script>
  <style>
    .article-wrapper {
      min-height: 200vh;
      position: relative;
      top: 0;
      left: 0;
    }

    .article-wrapper p:first-of-type {
      margin-top: 0;
    }

    footer {
      min-height: 100vh;
      background-color: lightskyblue;
    }

    .sidemenu-shares {
      z-index: 999;
      display: flex;
      flex-direction: column;
      align-items: center;
      height: 100%;
      justify-content: center;
      position: fixed;
      top: 0;
      right: 0;
      flex-wrap: nowrap;
      gap: 40px;
    }

    .rectangle {
      z-index: 998;
      transition: opacity 0.5s;
      padding: 5px;
      height: 106px;
      width: 123px;
      background-color: rgba(200, 0, 0, 0.1);
      border-radius: 24px;
    }

    .content {
      height: 50px;
      border: 1px dotted gray;
    }

  </style>
</head>

<body>
  <div id="wrapper" class="article-wrapper">

    <div id='sideMenu' class="sidemenu-shares">
      <div id="navShareLink" class="rectangle">

      </div>
    </div>

    <div class="main-banner">
      <h1>Title</h1>
    </div>

    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
    <div class='content'>Main content...</div>
  </div>

  <footer id='footer'>
    Footer...
  </footer>
</body>

</html>

Now it turns out that in my sideMenu there is only one block, but I want to add another one and so that they hide and open together

This is how the code should look like after adding the block

<div id='sideMenu' class="sidemenu-shares">
    <div id="navShareLink" class="rectangle">

    </div>

    <div id="navToTop" class="to-top">

    </div>
</div>

But now I can’t make them both hide

I am trying to do the following in js

nsl = document.querySelectorAll("#navShareLink, #navToTop");

But everything works incorrectly and nothing is hiding at all

Get cookie value by name and change style DOM element

Get cookie value by name and change style DOM element. I want to get the Arabic language from cookie and change the style of div to “dir=rtl” but I don’t know I can do this in one function

   <h2 class="text">{% translate 'Admin' %}</h2>
       <form class="login-form" method="post">
             {% csrf_token %}
            <div class="login-form">
                  {% include 'form_login.html' with field=form.username %}
             </div>             
        </form>
</div>
<style>
Object.defineProperty(window, "Cookies", {
    get: function() {
        return document.cookie.split(';').reduce(function(cookies, cookie) {
            cookies[cookie.split("=")[0]] = unescape(cookie.split("=")[1]);
            return cookies
        }, {});                                                                         ```                                                                                           there I want to get language and if this is Arabic do change of class="login-form" to style dir="rtl"                                                                              ```
    }
});
</style>

Please how I can do this

assign variable to value of Dictionary Javascript

I am building a dictionary but I would like some of the values to contain variables. is there a way to pass a variable to the dictionary so I can assign a dot notation variable? the variables object will always have the same structure and the dictionary will be static and structured the same for each key value pair. essentially I want to pass the value from the dictionary to another function to handle the data.

main.js

import myDictionary from "myDictionary.js"

const variables ={
item:"Hello"
}
const data = myDictionary[key](variables)
console.log(data)


myDictionary.js

const myDictionary = {
key: variables.item
}

so the log should display hello. I know it willl be something straightforward but cant seem to figure it out.

as always any help is greatly appreciated