MongoServerError: Authentication failed when using mongo and mongo express with docker containers

I am learning docker so I was following one of the video it shown that how to connect your js app with mongoDB when it is running in docker containers . Now little variation I did is that it shown to connect mongo on system port 27017 which is default mongo port but the problem is I don’t want to connect to my system installed mongo but to the container mongo , so for that purpose I decided to run mongo container on port 3535. When I did so mongo-express successfully got connected to mongo but when I am trying to connect it with my js app(using mongoose ) it is continuously showing errors with authentication error I have checked password is correct , no brackets issue is their , the command I used to turn up my docker containers are

docker run -d -p 3535:27017 --name mongoDB --network databases -e MONGO_INITDB_ROOT_USERNAME=admin -e MONGO_INITDB_ROOT_PASSWORD=admin mongo

and another one for mongo-express is

docker run -d -p 8081:8081 --name mongoExp --network databases -e ME_CONFIG_BASICAUTH_USERNAME=admin -e ME_CONFIG_BASICAUTH_PASSWORD=admin -e ME_CONFIG_MONGODB_SERVER=mongoDB -e ME_CONFIG_MONGODB_AUTH_USERNAME=admin -e ME_CONFIG_MONGODB_AUTH_PASSWORD=admin mongo-express

My node app code looks like

const mongoose = require('mongoose');
const {Humans}= require("./models/humans.js")
mongoose.connect('mongodb://admin:admin@localhost:3535/user', {useNewUrlParser: true, useUnifiedTopology: true }).then(()=>{
    console.log("connected to db");
})

let data={
    name:"Vaibhav Jain",
    mob:"9801",
    skills:"coding"
}

const express = require('express')
const app = express();
app.set('view engine', 'ejs');


app.get("/",async(req,res)=>{
    // console.log(Humans);
    // await Humans.insertMany( );
    // await Humans.insertMany({name:"Mobius" , mob:"5908922",skills:"drawing"});
    const result = await Humans.find();
    res.send(result);   
    
})
app.get("/home",(req,res)=>{
    res.render("home", data);
})

app.listen(3000,()=>{
    console.log("listening port");
})

Also one thing i would like to mention I have created a user database which have a collection human , this all I created from UI but I wanted to connect it to my app using mongoose , so for that Human which is shown to be imported is actually empty schema (read that from somewhere that you can use existing collections in such a way please correct me on this part also if I am wrong )

Convert Hex to base64 in react js

enter image description here

I am Fetch thumbnail path from localhost 8080 and wanted to convert it into hex to base64 (Already a hex coded ) and then show the image. how this Is done in react js and display the image in the IMG tag. please help

//CODE

import React, { Component } from "react";
import ReactDOM from "react-dom";
import ColumnResizer from "column-resizer";
import "./table.css"
import axios from "axios";  
   
class ReactTable extends Component {
  constructor(props) {
    super(props);
    this.tableSelector = "#somethingUnique";
    this.state = {
      Data: [],
      Data1: [],
      error: '',
      image: [],
    }
  }    
  //Fetching Api through LocalHost8080
  getFetchData() {
    axios.get(' /AmpRestAPI/webresources/getPCRList/all',
      {
        headers: {
          'Access-Control-Allow-Origin': '*',
        },
        auth: {
          username: 'admin',
          password: 'password'
        }
      })
      .then(async (response) => {
        console.log(response.data);
        this.setState({ Data: response.data });

      }).catch(error => {
        this.setState({ error: 'unable to fetch URL' });
        console.log(error.response);
      });
  }          
  componentDidMount() {    
    if (this.props.resizable) {
      this.enableResize();
      this.getFetchData();
    }
  }   
  render() {
    const { Data, error } = this.state
    return (
      <div>

        <div className="container-fluid pt-3">
          <table id="somethingUnique" cellSpacing="0" className="border-primary">
            <thead>                  
            </thead>
            <tbody>
              {Data.length ?
                Data.map((val, index) => {
                  //flitter
                  const filterValue = this.props.filterValue;
                  const emplogin = val.ChannelName.toLowerCase();
                  // const emptype = emp.type;
                  if (((!filterValue) || (emplogin.indexOf(filterValue) !== -1))) {
                    return (
                      <tr key={index}>
                        <td>
                          {this.state.image ? <img src={`data:image/jpeg;base64,${val.Thumbnail}`} alt="Clip Thumbnail" width="100%" height="100%" /> : ''}
                        </td>
                        <td>
                            {val.ChannelName}
                         </td>
                        <td>{val.Duration}  </td>                       
                          <td>  {val.EndTime}
                          </td>
                        <td>
                            {val.LoadedClip}
                         </td>
                        <td>
                            {val.StartTime}
                         </td>

                        <td>
                            {val.CurrentTimeStamp}
                        </td>
                      </tr>
            )
                  }
            return true;
                }
            ) : null
              }
          </tbody>
        </table>
        {
          error ? <div className="text-center pt-4"><h5>{error}</h5></div> : null
        }
      </div >
      </div >
    );
  }
}    
export default ReactTable;

I am Fetch thumbnail path from localhost 8080 and wanted to convert it into hex to base64 (Already a hex coded ) and then show the image. how this Is done in react js and display the image in the IMG tag. please help

Pass a laravel variable into a jquery array

I am trying to pass a variable into a jquery autocomplete script check this url (https://jsfiddle.net/duoc5bbh/1/) I found.

Laravel

@foreach($data as $value)
   {{ $value-> email }}
   {{ $value-> name }}
@endforeach

Jquery

$(function() {
  let users = [{
      "email": "[email protected]",
      "name": "marie"
      }, 
      {
       "email": "[email protected]",
       "name": "miss"
     }];
});

what I did

$(function() {
  let users = [{
      "email": {{ $value-> email }},
      "name": {{ $value-> name }}
      }];
});

I am new in using laravel with jquery I need your help in this Thanks.

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

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++;
    }

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/

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’.