0
votes

Installed Docker, downloaded the mysql image, using VS Code. This is my docker.compose.yml file:

version: '3'
services:
  db:
    image: mysql:latest
    environment:
      MYSQL_DATABASE: 'db'
      # So you don't have to use root, but you can if you like
      MYSQL_USER: 'root'
      # You can use whatever password you like
      MYSQL_PASSWORD: 'root'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'root'
    ports:
      # <Port exposed> : < MySQL Port running inside container>
      - '3306:3306'
    #security_opt:
      #- seccomp:unconfined
    cap_add:
      - SYS_NICE  # CAP_SYS_NICE
    expose:
      # Opens port 3306 on the container
      - '3306'
      # Where our data will be persisted
    volumes:
      # this creates paths on the container 
      - my-db:/var/lib/mysql
      - my-db:/docker-entrypoint-initdb.d
# Names our volume
volumes:
  my-db:    

With the command "docker compose up", I see and output, I see the image is running. I get this output:

  • Container irp-backend_db_1 Created 0.0s Attaching to db_1 db_1 | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.25-1debian10 started. db_1 | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql' db_1 | 2021-06-10 13:23:30+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.25-1debian10 started. db_1 | 2021-06-10T13:23:30.769957Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.25) starting as process 1 db_1 | 2021-06-10T13:23:30.791485Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started. db_1 | 2021-06-10T13:23:30.955342Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended. db_1 | 2021-06-10T13:23:31.047007Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock db_1 | 2021-06-10T13:23:31.153833Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed. db_1 | 2021-06-10T13:23:31.154004Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel. db_1 | 2021-06-10T13:23:31.158189Z 0 [Warning] [MY-011810] [Server] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory. db_1 | 2021-06-10T13:23:31.175606Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.25' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.

This is my config/config.json file:

{
  "development": {
    "username": "root",
    "password": "root",
    "database": "database_development",
    "host": "localhost",
    "dialect": "mysql"
  },
  "test": {
    "username": "root",
    "password": "root",
    "database": "database_test",
    "host": "localhost",
    "dialect": "mysql"
  },
  "production": {
    "username": "root",
    "password": "root",
    "database": "database_production",
    "host": "localhost",
    "dialect": "mysql"
  }
}

My migrations/create-user.js

module.exports = {
  up: async (queryInterface, Sequelize) => {
    await queryInterface.createTable('Users', {
      id: {
        allowNull: false,
        autoIncrement: true,
        primaryKey: true,
        type: Sequelize.INTEGER
      },
      email: {
        type: Sequelize.STRING,
        allowNull: false
      },
      password: {
        type: Sequelize.STRING,
        allowNull: false
      },
      firstName: {
        type: Sequelize.STRING
      },
      lasrName: {
        type: Sequelize.STRING
      },
      createdAt: {
        allowNull: false,
        type: Sequelize.DATE
      },
      updatedAt: {
        allowNull: false,
        type: Sequelize.DATE
      }
    });
  },
  down: async (queryInterface, Sequelize) => {
    await queryInterface.dropTable('Users');
  }
 };

models/index.js

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};

let sequelize;
if (config.use_env_variable) {
  sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
}

// go through all files and do sequelize
fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    db[model.name] = model;
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});

db.sequelize = sequelize;
db.Sequelize = Sequelize;

module.exports = db;

this is my model/User.js

const { Model } = require('sequelize');
module.exports = (sequelize, DataTypes) => {
  class User extends Model {
    /**
     * Helper method for defining associations.
     * This method is not a part of Sequelize lifecycle.
     * The `models/index` file will call this method automatically.
     */
    static associate(models) {
      // define association here
    }
  };
  User.init({
    email: DataTypes.STRING,
    password: DataTypes.STRING,
    firstName: DataTypes.STRING,
    lasrName: DataTypes.STRING
  }, {
    sequelize,
    modelName: 'User',
  });
  return User;
};

in order to have a more readable code I have a router routes/index.js

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

/**
 * router files
 */

const userRoutes = require("./user/index");
const clientRoutes  = require("./client/index");

/**
 * using route files
 */

router.use("/users", userRoutes);

router.get("/", (req, res) => {
  res.json({
    message: "????",
  });
});

module.exports = router;

and my user routes/user/index.js

const { Router } = require("express");
const router = Router();

const userController = require("../../controllers/UserController");

// get requests
router.get("/", userController.getUsers);
router.get("/getUserByEmail/:email", userController.getUserByEmail);

// post requests
router.post("/register", userController.register);
router.post("/login", userController.login);
router.post("/setUserPassword", userController.setUserPassword);

module.exports = router;

my package.json

{
  "name": "nodejs-express-sequelize-mysql",
  "version": "1.0.0",
  "description": "Node.js Rest Apis with Express, Sequelize & MySQL",
  "main": "server.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "nodejs",
    "express",
    "rest",
    "api",
    "sequelize",
    "mysql"
  ],
  "author": "bezkoder",
  "license": "ISC",
  "dependencies": {
    "cors": "^2.8.5",
    "express": "^4.17.1",
    "mysql2": "^2.0.2",
    "sequelize": "^5.21.2"
  }
}

my sequlize.js file

import Sequelize from 'sequelize'
import UserModel from "./models/User"

TAG = "sequelize"

                                     // fields in the config.json file
const sequelizeSqlite = new Sequelize("database", "username", "password", {
    dialect: 'sqlite',
    storage: "data/db/storage.sqlite"
})

const UserSqlite = UserModel(sequelizeSqlite, Sequelize);

sequelizeSqlite.sync()
    .then(() => {
        console.log(TAG, "User db and user table have been created  with Sqlite");
    })

module.exports(UserSqlite);

and last file server.js file: app.use(express.urlencoded({ extended: true }));

const db = require("./models");
db.sequelize.sync();

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to The Backend." });
});

app.use("./api", routes);

// set port, listen for requests
const PORT = process.env.PORT || 3000;

app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});
  1. I run: docker compose up ... image is working, I can see it on the Docker for Windows
  2. I run node server.js ... it creates a table on the image, I can see it on the docker extension
  3. I can't run the project with npm start

I get the following error:

  [email protected] start C:\Users\Win-10\Desktop\IRP\irp-backend
 > node server.js

 events.js:353
       throw er; // Unhandled 'error' event
       ^

 Error: listen EADDRINUSE: address already in use :::3000
     at Server.setupListenHandle [as _listen2] (net.js:1318:16)
     at listenInCluster (net.js:1366:12)
     at Server.listen (net.js:1452:7)
     at Function.listen (C:\Users\Win-10\Desktop\IRP\irp-     backend\node_modules\express\lib\application.js:618:24)
     at Object.<anonymous> (C:\Users\Win-10\Desktop\IRP\irp-backend\server.js:32:5)
     at Module._compile (internal/modules/cjs/loader.js:1068:30)
     at Object.Module._extensions..js (internal/modules/cjs/loader.js:1097:10)
     at Module.load (internal/modules/cjs/loader.js:933:32)
     at Function.Module._load (internal/modules/cjs/loader.js:774:14)
     at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
     at internal/main/run_main_module.js:17:47
  Emitted 'error' event on Server instance at:
     at emitErrorNT (net.js:1345:8)
     at processTicksAndRejections (internal/process/task_queues.js:82:21) {
   code: 'EADDRINUSE',
   errno: -4091,
   syscall: 'listen',
   address: '::',
   port: 3000
 }

I can see the backend is working in browser localhost:3000 White page with one line displayed: {"message":"Welcome to The Backend."} // my msg from server.js

I am still missing something but I cant figure it out. Can you please help me.

1

1 Answers

0
votes

This error line Error: listen EADDRINUSE: address already in use :::3000 and the localhost:3000 response, suggest that the server.js is up and running at PORT:3000.

npm start is the same as running node server.js ( i don't see it at package.json at scripts but i guess it's there).

So... try one or the other. It's like trying to access the same port with 2 different scripts.

I hope i get it right.

Actually, why you declare in 2 places new Sequelize(...) instance. Also why your config has sqlite and not mysql2? Maybe i misunderstand