react project compiles but not working - node.js

I am on my reactjs project. I run gulp command to compile the project. During compile i get few errors and still the project compiles succcessfully. But I am not able to run my application. I am sure it is because of compile errors.
This is my compile console
Apurvs-MacBook-Pro:tessact-client-2 apurvgandhwani$ gulp
[01:52:51] Failed to load external module #babel/register
[01:52:51] Requiring external module babel-register
[01:52:54] Using gulpfile ~/Desktop/tessact-client-2/tessact-client-2/gulpfile.babel.js
[01:52:54] Starting 'build:watch'...
[01:52:54] Starting 'copy:assets'...
[01:52:54] Starting 'copy:vendors'...
Cleaned build/
Copied 14 asset entries.
[01:52:54] Finished 'copy:vendors' after 157 ms
[01:52:54] Starting 'copy:views'...
[01:52:54] copied views all files 1.79 kB
[01:52:54] Finished 'copy:views' after 60 ms
[01:52:54] Starting 'copy:public'...
[01:52:54] Finished 'copy:public' after 29 ms
[01:52:54] Finished 'copy:assets' after 248 ms
[01:52:54] Starting 'bundle:dll'...
DLL Bundled.
Hash: 0c28a0c5268f8a4b023c
Version: webpack 1.15.0
Time: 2362ms
Asset Size Chunks Chunk Names
dll.vendor.js 3.16 MB 0 [emitted] vendor
[01:52:57] Finished 'bundle:dll' after 2.4 s
[01:52:57] Starting 'bundle'...
Hash: d2622522a127e8235b84
Version: webpack 1.15.0
Time: 641ms
Asset Size Chunks Chunk Names
server-bundle.js 65 kB 0 [emitted] main
-- server:watch bundled.
Hash: b86595a12c8058d77ded
Version: webpack 1.15.0
Time: 6049ms
Asset Size Chunks Chunk Names
00103e881a36640a08f869ff6888f0fd.eot 5.9 kB [emitted]
main-bundle.js 3.13 MB 0 [emitted] main
-- client bundled.
[01:53:03] Finished 'bundle' after 6.05 s
[01:53:03] Starting 'start:server'...
Starting Node Server...
[01:53:03] Finished 'start:server' after 147 ms
[01:53:03] Starting 'watch:sync'...
[01:53:03] [nodemon] 1.14.11
[01:53:03] [nodemon] to restart at any time, enter `rs`
[01:53:03] [nodemon] watching: build/server-bundle.js
[01:53:03] [nodemon] starting `node --debug --inspect build/server-bundle.js`
Server Restarted: Reloading BrowserSync.
Debugger listening on ws://127.0.0.1:9229/c6e6fdcb-9801-4097-b9cb-7480c39f4380
For help see https://nodejs.org/en/docs/inspector
[tessact: ] Proxying: http://localhost:4200
[tessact: ] Access URLs:
-------------------------------------
Local: http://localhost:3000
External: http://192.168.0.32:3000
-------------------------------------
UI: http://localhost:3001
UI External: http://192.168.0.32:3001
-------------------------------------
[tessact: ] Watching files...
[01:53:03] Finished 'watch:sync' after 224 ms
[01:53:03] Starting 'watch:assets'...
[01:53:03] Finished 'watch:assets' after 14 ms
[01:53:03] Finished 'build:watch' after 9.09 s
[01:53:03] Starting 'default'...
[01:53:03] Finished 'default' after 28 Ξs
tessact:db DBERROR: connect ECONNREFUSED 127.0.0.1:3306 +0ms
ServerStartupError: { Error: connect ECONNREFUSED 127.0.0.1:3306
at Object._errnoException (util.js:1003:13)
at _exceptionWithHostPort (util.js:1024:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1194:14)
at Protocol._enqueue (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/node_modules/mysql/lib/protocol/Protocol.js:145:48)
at Protocol.handshake (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/node_modules/mysql/lib/protocol/Protocol.js:52:23)
at Connection.connect (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/node_modules/mysql/lib/Connection.js:130:18)
at /Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/src/server/db.js:26:14
From previous event:
at initDB (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/src/server/db.js:25:9)
at Object.defineProperty.value (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/src/server/app.js:27:1)
at __webpack_require__ (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/webpack/bootstrap d2622522a127e8235b84:19:1)
at Object.<anonymous> (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/server-bundle.js:48:19)
at __webpack_require__ (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/webpack/bootstrap d2622522a127e8235b84:19:1)
at /Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/webpack:/webpack/bootstrap d2622522a127e8235b84:39:1
at Object.<anonymous> (/Users/apurvgandhwani/Desktop/tessact-client-2/tessact-client-2/build/server-bundle.js:44:10)
at Module._compile (module.js:660:30)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:193:16)
at bootstrap_node.js:617:3
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true }
[tessact: ] Reloading Browsers...
[01:53:05] [nodemon] clean exit - waiting for changes before restart
webpack built b86595a12c8058d77ded in 3199ms
Hash: b86595a12c8058d77ded
Version: webpack 1.15.0
Time: 3199ms
Asset Size Chunks Chunk Names
00103e881a36640a08f869ff6888f0fd.eot 5.9 kB [emitted]
main-bundle.js 3.13 MB 0 main
webpack: Compiled successfully.
There is an error in the starting and one in the middle of the snippet.
This is my config.js file
const IS_PROD = (process.env.NODE_ENV === "production");
// const IS_PROD = false;
const NODE_PORT = 4211;
const BS_PORT = 3002;
module.exports = {
NODE_PORT,
BS_PORT,
SESSION_SECRET: 't355#c7_S3cr37',
LOGIN_URL: "https://www.backend.trigger.tessact.com/auth/login/",
DB: {
production: {
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'tessact_db'
},
development: {
host: 'localhost',
port: 3306,
user: 'root',
password: '',
database: 'tessact_db'
}
},
ACL_POPULATION_URL: '/populate',
ACL_UPDATE_URL: '/update-acl-population'
}
This is my configure.js file
import express from 'express'
import path from 'path'
import favicon from 'serve-favicon'
import logger from 'morgan'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import compression from 'compression'
import session from 'express-session'
import config from './config'
import getRoutes from './routes'
const IS_PROD = process.env.NODE_ENV === 'production';
export default function configureServer(db, app){
const loggerMode = IS_PROD ? 'combined' : 'dev'
const env = IS_PROD ? 'production' : 'development'
const MySQLStore = require('express-mysql-session')(session)
app.set('env', env);
app.use(logger(loggerMode));
// Pretty prints template output
if (!IS_PROD) {
app.locals.pretty = true;
}
// Where to find templates
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(compression());
// Server static assets from this directory
app.use('/public',
express.static( path.resolve(__dirname, './public'))
);
// Should come after static assets
// Otherwise static requests will be treated with cookies and session as well
app.use(cookieParser(config.SESSION_SECRET));
app.use(
session({
resave: true,
saveUninitialized: true,
secret: config.SESSION_SECRET,
store: new MySQLStore({}, db)
})
)
// Add routes
app.use('/', getRoutes(db, app));
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
return Promise.resolve({db, app})
}
This is my db.js
import Promise from 'bluebird';
import config from './config';
import mysql from 'mysql';
var debug = require('debug')('tessact:db');
const IS_PROD = (process.env.NODE_ENV !== "production");
const connOptions = config.DB[
IS_PROD ? 'production' : 'development'
]
var connection = mysql.createConnection(connOptions)
process.on('SIGTERM', ()=> {
connection.end(err=> {
if (error){
console.error(err);
}
debug('DB Closed');
})
});
const initDB = ()=> {
return new Promise((resolve, reject)=>{
connection.connect(err => {
if (err){
debug('DBERROR: ', err.message)
return reject(err)
}
debug('Connected')
resolve(connection)
})
});
}
export default initDB;

Your application fails to connect to the database (I assume mysql). It tries to connect to localhost:3306 and gets connect ECONNREFUSED 127.0.0.1:3306 which usually means there is no mysql listening on this server.
You should either start mysql on the same machine, or configure your application to connect to a remote mysql.
It is also possible that you have a database running but listening on a different port or network-interface.

Related

Node.js v18.13.0 [nodemon] app crashed - waiting for file changes before starting... - How can I fix it?

I'm trying to clone whatsapp.. I've done with frontend part.. but when I try to connect with mongodb and get & post a request through postman api... but my code is getting crashed.
I'm using "type":"module" in package.json
This is what i'm getting in terminal
Listening on localhost:9000
D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282
throw new error_1.MongoParseError(`${optionWord} ${Array.from(unsupportedOptions).join(', ')} ${isOrAre} not supported`);
^
MongoParseError: option usecreateindex is not supported
at parseOptions (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\connection_string.js:282:15)
at new MongoClient (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongodb\lib\mongo_client.js:45:63)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:802:16
at new Promise (<anonymous>)
at Connection.openUri (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\connection.js:799:19)
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:409:10
at D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:41:5
at new Promise (<anonymous>)
at promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\helpers\promiseOrCallback.js:40:10)
at Mongoose._promiseOrCallback (D:\Project\Guvi\Task\React\clone-whatsapp\wa-back\node_modules\mongoose\lib\index.js:1262:10) {
[Symbol(errorLabels)]: Set(0) {}
}
Node.js v18.13.0
[nodemon] app crashed - waiting for file changes before starting...
import express from 'express';
import mongoose from 'mongoose';
import Messages from './dbMessages.js';
const app = express();
const port = process.env.PORT || 9000;
app.use(express.json());
const connection_url = 'mongodb+srv://sarath_babayaga:Sarath#1996#cluster0.wzoouq0.mongodb.net/clone-whatsapp-backend? retryWrites=true&w=majority'
mongoose.connect(connection_url,{
useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true
})
app.get('/',(req,res)=>res.status(200).send('hello world!!!!'));
app.get('/messages/sync', (req, res) => {
const dbMessage = req.body
Messages.find ((err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(200).send(data)
}
})
})
app.post('/messages/new', (req, res) => {
const dbMessage = req.body
Messages.create(dbMessage, (err, data) => {
if (err) {
res.status(500).send(err)
} else {
res.status(201).send(data)
}
})
})
app.listen(port,()=>console.log(`Listening on localhost:${port}`));
according to the official forum of MongoDB, UseCreateIndex is deprecated since Mongoose 6, so I think this is the issue. Try removing useCreateIndex from your code
https://www.mongodb.com/community/forums/t/option-usecreateindex-is-not-supported/123048/3

Forest Admin returns 404 for /forest/authentication route

I am not able to set up Forest Admin with my local environment (Express and MySQL). When I try to authenticate, I am getting 404 for /forest/authentication route.
app.js
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const jwt = require('express-jwt');
const Sequelize = require('sequelize');
const forest = require('forest-express-sequelize');
const { errorHandler } = require('forest-express-sequelize');
// const { createAgent } = require('#forestadmin/agent');
// const {
// createSequelizeDataSource,
// } = require('#forestadmin/datasource-sequelize');
require('dotenv').config();
const cors = require('cors');
const sequelizeInstance = require('./src/db/models/index').sequelize;
var indexRouter = require('./src/routes/index');
var authRouter = require('./src/routes/api/auth');
var usersRouter = require('./src/routes/api/users');
var ceremonyRouter = require('./src/routes/api/ceremony');
var questionRouter = require('./src/routes/api/questions');
var app = express();
let allowedOrigins = [
/\.forestadmin\.com$/,
/localhost:\d{4}$/,
'http://localhost:6868',
];
var corsOptions = {
origin: allowedOrigins,
maxAge: 86400, // NOTICE: 1 day
credentials: true,
};
// Support for request-private-network as the `cors` package
// doesn't support it by default
// See: https://github.com/expressjs/cors/issues/236
app.use((req, res, next) => {
if (req.headers['access-control-request-private-network']) {
res.setHeader('access-control-allow-private-network', 'true');
}
next(null);
});
app.use(
'/forest/authentication',
cors({
...corsOptions,
// The null origin is sent by browsers for redirected AJAX calls
// we need to support this in authentication routes because OIDC
// redirects to the callback route
origin: corsOptions.origin.concat('null'),
})
);
app.use(cors(corsOptions));
// view engine setup
app.set('views', path.join(__dirname, 'src/views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use('/', indexRouter);
app.use('/api', indexRouter);
app.use('/api/auth', authRouter);
app.use('/api/users', usersRouter);
app.use('/api/ceremony', ceremonyRouter);
app.use('/api/questions', questionRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
// set port, listen for requests
const PORT = process.env.NODE_DOCKER_PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
// // Create your Forest Admin agent
// // This must be called BEFORE all other middlewares on the express app
// createAgent({
// authSecret: process.env.FOREST_AUTH_SECRET,
// agentUrl: process.env.FOREST_AGENT_URL,
// envSecret: process.env.FOREST_ENV_SECRET,
// isProduction: process.env.NODE_ENV === 'production',
// })
// .addDataSource(createSequelizeDataSource(sequelizeInstance))
// .mountOnExpress(app)
// .start();
app.use(
jwt({
secret: process.env.FOREST_AUTH_SECRET,
credentialsRequired: false,
algorithms: ['HS256'],
})
);
forest
.init({
envSecret: process.env.FOREST_ENV_SECRET,
authSecret: process.env.FOREST_AUTH_SECRET,
objectMapping: Sequelize,
connections: { default: sequelizeInstance },
})
.then((FAMiddleware) => {
app.use(FAMiddleware);
});
app.use(errorHandler());
module.exports = app;
package.json
{
"name": "backend",
"version": "0.0.0",
"private": true,
"scripts": {
"start": "node ./bin/www",
"start_dev": "nodemon ./bin/www",
"docker": "docker-compose up --build"
},
"dependencies": {
"#forestadmin/agent": "1.0.0-beta.43",
"#forestadmin/datasource-sequelize": "1.0.0-beta.34",
"bcryptjs": "^2.4.3",
"cookie-parser": "~1.4.4",
"cors": "^2.8.5",
"date-and-time": "^2.4.1",
"debug": "~2.6.9",
"dotenv": "^16.0.1",
"express": "~4.16.1",
"express-jwt": "6.1.2",
"express-validator": "^6.14.2",
"forest-express-sequelize": "8.5.11",
"handlebars": "^4.7.7",
"handlebars-helpers": "^0.10.0",
"http-errors": "~1.6.3",
"jade": "^0.29.0",
"jsonwebtoken": "^8.5.1",
"mailgun.js": "^8.0.0",
"moment": "^2.29.4",
"morgan": "~1.9.1",
"mysql2": "^2.3.3",
"nodemailer": "^6.7.7",
"passport": "^0.6.0",
"passport-jwt": "^4.0.0",
"rand-token": "^1.0.1",
"sequelize": "^6.21.3",
"sequelize-auto": "^0.8.8"
},
"devDependencies": {
"nodemon": "^2.0.19",
"sequelize-cli": "^6.4.1"
}
}
docker-compose.yml
version: '3.8'
services:
mysqldb:
platform: linux/x86_64
image: mysql:8.0.29
restart: unless-stopped
env_file: ./.env
environment:
- MYSQL_ROOT_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- MYSQL_DATABASE=$MYSQLDB_DATABASE
ports:
- $MYSQLDB_LOCAL_PORT:$MYSQLDB_DOCKER_PORT
volumes:
- db:/var/lib/mysql
phpmyadmin:
image: phpmyadmin/phpmyadmin
ports:
- 11819:80
depends_on:
- mysqldb
environment:
PMA_HOSTS: mysqldb
PMA_USER: $MYSQLDB_USER
PMA_PASSWORD: $MYSQLDB_ROOT_PASSWORD
UPLOAD_LIMIT: 100M
app:
depends_on:
- mysqldb
build:
context: .
network: host
restart: unless-stopped
env_file: ./.env
volumes:
- .:/var/www/app
working_dir: /var/www/app
ports:
- $NODE_LOCAL_PORT:$NODE_DOCKER_PORT
environment:
- DB_HOST=mysqldb
- DB_USER=$MYSQLDB_USER
- DB_PASSWORD=$MYSQLDB_ROOT_PASSWORD
- DB_NAME=$MYSQLDB_DATABASE
- DB_PORT=$MYSQLDB_DOCKER_PORT
stdin_open: true
tty: true
volumes:
db:
The Node.js project is running on localhost:6868 without any issues:
terminal log
andand#And-MacBook-Pro backend % docker-compose up --build
[+] Building 42.5s (10/10) FINISHED
=> [internal] load build definition from Dockerfile 0.0s
=> => transferring dockerfile: 32B 0.0s
=> [internal] load .dockerignore 0.0s
=> => transferring context: 2B 0.0s
=> [internal] load metadata for docker.io/library/node:16 0.6s
=> [internal] load build context 0.5s
=> => transferring context: 2.11MB 0.5s
=> CACHED [1/6] FROM docker.io/library/node:16#sha256:1ed1e17ccabb09038cfb8a965337ebcda51ef9e9d32082164c502d 0.0s
=> [2/6] COPY package.json . 0.0s
=> [3/6] RUN npm install -g nodemon 3.6s
=> [4/6] RUN npm install 35.6s
=> [5/6] COPY . . 1.0s
=> exporting to image 1.1s
=> => exporting layers 1.1s
=> => writing image sha256:53f94f35be4528c5cd899f5702e433acf915a3b1d01a2dbdf098d35482a42bf5 0.0s
=> => naming to docker.io/library/backend_app 0.0s
Use 'docker scan' to run Snyk tests against images to find vulnerabilities and learn how to fix them
[+] Running 3/3
â ŋ Container backend-mysqldb-1 Created 0.0s
â ŋ Container backend-app-1 Recreated 0.1s
â ŋ Container backend-phpmyadmin-1 Created 0.0s
Attaching to backend-app-1, backend-mysqldb-1, backend-phpmyadmin-1
backend-mysqldb-1 | 2022-08-09 14:22:50+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
backend-phpmyadmin-1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.18.0.3. Set the 'ServerName' directive globally to suppress this message
backend-phpmyadmin-1 | AH00558: apache2: Could not reliably determine the server's fully qualified domain name, using 172.18.0.3. Set the 'ServerName' directive globally to suppress this message
backend-phpmyadmin-1 | [Tue Aug 09 14:22:51.704530 2022] [mpm_prefork:notice] [pid 1] AH00163: Apache/2.4.53 (Debian) PHP/8.0.19 configured -- resuming normal operations
backend-phpmyadmin-1 | [Tue Aug 09 14:22:51.706056 2022] [core:notice] [pid 1] AH00094: Command line: 'apache2 -D FOREGROUND'
backend-mysqldb-1 | 2022-08-09 14:22:51+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
backend-app-1 | [nodemon] 2.0.19
backend-app-1 | [nodemon] to restart at any time, enter `rs`
backend-app-1 | [nodemon] watching path(s): *.*
backend-app-1 | [nodemon] watching extensions: js,mjs,json
backend-app-1 | [nodemon] starting `node /var/www/app/app.js npm run start_dev`
backend-mysqldb-1 | 2022-08-09 14:22:51+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 8.0.29-1.el8 started.
backend-mysqldb-1 | '/var/lib/mysql/mysql.sock' -> '/var/run/mysqld/mysqld.sock'
backend-mysqldb-1 | 2022-08-09T14:22:53.698645Z 0 [System] [MY-010116] [Server] /usr/sbin/mysqld (mysqld 8.0.29) starting as process 1
backend-mysqldb-1 | 2022-08-09T14:22:53.808611Z 1 [System] [MY-013576] [InnoDB] InnoDB initialization has started.
backend-mysqldb-1 | 2022-08-09T14:22:53.846153Z 1 [ERROR] [MY-012585] [InnoDB] Linux Native AIO interface is not supported on this platform. Please check your OS documentation and install appropriate binary of InnoDB.
backend-mysqldb-1 | 2022-08-09T14:22:53.846650Z 1 [Warning] [MY-012654] [InnoDB] Linux Native AIO disabled.
backend-mysqldb-1 | 2022-08-09T14:22:54.473510Z 1 [System] [MY-013577] [InnoDB] InnoDB initialization has ended.
backend-mysqldb-1 | 2022-08-09T14:22:55.462049Z 0 [System] [MY-010229] [Server] Starting XA crash recovery...
backend-mysqldb-1 | 2022-08-09T14:22:55.478820Z 0 [System] [MY-010232] [Server] XA crash recovery finished.
backend-mysqldb-1 | 2022-08-09T14:22:55.754773Z 0 [Warning] [MY-010068] [Server] CA certificate ca.pem is self signed.
backend-mysqldb-1 | 2022-08-09T14:22:55.756819Z 0 [System] [MY-013602] [Server] Channel mysql_main configured to support TLS. Encrypted connections are now supported for this channel.
backend-mysqldb-1 | 2022-08-09T14:22:55.774738Z 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.
backend-mysqldb-1 | 2022-08-09T14:22:56.089136Z 0 [System] [MY-011323] [Server] X Plugin ready for connections. Bind-address: '::' port: 33060, socket: /var/run/mysqld/mysqlx.sock
backend-mysqldb-1 | 2022-08-09T14:22:56.091257Z 0 [System] [MY-010931] [Server] /usr/sbin/mysqld: ready for connections. Version: '8.0.29' socket: '/var/run/mysqld/mysqld.sock' port: 3306 MySQL Community Server - GPL.
backend-app-1 | [forest] ðŸŒģðŸŒģðŸŒģ Your configDir ("/var/www/app/forest") does not exist. Please make sure it is set correctly.
backend-app-1 | Server is running on port 8080.
backend-app-1 | [forest] ðŸŒģðŸŒģðŸŒģ Checking need for apimap update...
backend-app-1 | Executing (default): SELECT 1+1 AS result
backend-app-1 | Connection has been established successfully.
backend-app-1 | [forest] ðŸŒģðŸŒģðŸŒģ No change in apimap, nothing sent to Forest.
backend-app-1 | POST /forest/authentication 404 315.425 ms - 1916
backend-app-1 | GET / 304 16.272 ms - -
backend-app-1 | GET /stylesheets/style.css 304 2.196 ms - -
db/models/index.js
'use strict';
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/database.js')[env];
const db = {};
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], {
...config,
host: process.env.USING_DOCKER ? 'host.docker.internal' : config.host,
});
} else {
sequelize = new Sequelize(config.database, config.username, config.password, {
...config,
host: process.env.USING_DOCKER ? 'host.docker.internal' : config.host,
});
}
sequelize
.authenticate()
.then(() => {
console.log('Connection has been established successfully.');
})
.catch((err) => {
console.error('Unable to connect to the database:', err);
});
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;
module.exports = db;
I tried to change:
app.use(
'/forest/authentication',
cors({
...corsOptions,
// The null origin is sent by browsers for redirected AJAX calls
// we need to support this in authentication routes because OIDC
// redirects to the callback route
origin: corsOptions.origin.concat('null'),
})
);
to this
const watchRouter = new express.Router();
watchRouter.post(
'/authentication',
cors({
...corsOptions,
// The null origin is sent by browsers for redirected AJAX calls
// we need to support this in authentication routes because OIDC
// redirects to the callback route
origin: corsOptions.origin.concat('null'),
})
);
app.use('/forest', watchRouter);
but it didn't help. I am still getting POST /forest/authentication 404.
I changed the code to this and it's working now:
const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const { createAgent } = require('#forestadmin/agent');
const {
createSequelizeDataSource,
} = require('#forestadmin/datasource-sequelize');
require('dotenv').config();
const cors = require('cors');
const sequelizeInstance = require('./src/db/models/index').sequelize;
var indexRouter = require('./src/routes/index');
var authRouter = require('./src/routes/api/auth');
var usersRouter = require('./src/routes/api/users');
var ceremonyRouter = require('./src/routes/api/ceremony');
var questionRouter = require('./src/routes/api/questions');
var app = express();
// Create your Forest Admin agent
// This must be called BEFORE all other middlewares on the express app
createAgent({
authSecret: process.env.FOREST_AUTH_SECRET,
agentUrl: process.env.FOREST_AGENT_URL,
envSecret: process.env.FOREST_ENV_SECRET,
isProduction: process.env.NODE_ENV === 'production',
})
.addDataSource(createSequelizeDataSource(sequelizeInstance))
.mountOnExpress(app)
.start();
let allowedOrigins = [/\.forestadmin\.com$/, /localhost:\d{4}$/];
if (process.env.ALLOWED_CORS) {
allowedOrigins = allowedOrigins.concat(process.env.ALLOWED_CORS.split(','));
}
var corsOptions = {
origin: allowedOrigins,
};
app.use(cors(corsOptions));
// view engine setup
app.set('views', path.join(__dirname, 'src/views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use('/', indexRouter);
app.use('/api', indexRouter);
app.use('/api/auth', authRouter);
app.use('/api/users', usersRouter);
app.use('/api/ceremony', ceremonyRouter);
app.use('/api/questions', questionRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
res.status(err.status || 500);
res.render('error');
});
// set port, listen for requests
const PORT = process.env.NODE_DOCKER_PORT || 8080;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}.`);
});
module.exports = app;

Couldn't resolve the error coming for mongodb atlas after deploying it on heroku?

In locally the application works perfectly but when i deployed it on heroku it showing errors on heroku logs. Also data wasn't added in mongoDb database. Actually in the application i used google-oauth login so in locally it works perfectly but not in heroku. I've also whitelisted my ip on mongodb atlas but still can't figure out why this error getting.
Anybody help me plz.....
Here is my prod.js file
module.exports = {
googleClientID: process.env.GOOGLE_CLIENT_ID,
googleClientSecret: process.env.GOOGLE_CLIENT_SECRET,
mongoURI: process.env.MONGO_URI,
cookieKey: process.env.COOKIE_KEY
}
Here is my keys.js file
// Keys.js - figure out what credentials should return
if (process.env.NODE_ENV === "production") {
// So we are in prodution - return the prod set of keys
module.exports = require('./prod');
} else {
// We are developement - return the dev keys
module.exports = require('./dev');
}
Here is my index.js file
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const cookieSession = require('cookie-session');
const keys = require('./config/keys');
require('./models/User');
require('./services/passport');
const app = express();
//Middleware
app.use(
cookieSession({
maxAge: 30 * 24 * 60 * 60 * 1000,
keys: [keys.cookieKey]
})
);
app.use(passport.initialize());
app.use(passport.session());
// mongoDb Connection
mongoose.connect(keys.mongoURI, {
useNewUrlParser: true
}).then(() => console.log('MongoDb Connect successfully'))
.catch(err => console.log(err));
// actual routes
require('./routes/authRoutes')(app);
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => console.log(`Server is running in ${PORT}`));
Actually i getting two different errors first was this
2019-09-02T06:28:59.760121+00:00 app[web.1]: Warning: connect.session() MemoryStore is not
2019-09-02T06:28:59.760149+00:00 app[web.1]: designed for a production environment, as it will leak
2019-09-02T06:28:59.760151+00:00 app[web.1]: memory, and will not scale past a single process.
2019-09-02T06:28:59.763577+00:00 app[web.1]:
2019-09-02T06:28:59.763581+00:00 app[web.1]: /app/node_modules/mongoose/lib/connection.js:519
2019-09-02T06:28:59.763583+00:00 app[web.1]: throw new MongooseError('The `uri` parameter to `openUri()` must be a ' +
2019-09-02T06:28:59.763585+00:00 app[web.1]: ^
2019-09-02T06:28:59.763838+00:00 app[web.1]: MongooseError: The `uri` parameter to `openUri()` must be a string, got "undefined". Make sure the first parameter to `mongoose.connect()` or `mongoose.createConnection()` is a string.
2019-09-02T06:28:59.763842+00:00 app[web.1]: at new MongooseError (/app/node_modules/mongoose/lib/error/mongooseError.js:10:11)
2019-09-02T06:28:59.763844+00:00 app[web.1]: at NativeConnection.Connection.openUri (/app/node_modules/mongoose/lib/connection.js:519:11)
2019-09-02T06:28:59.763846+00:00 app[web.1]: at Mongoose.connect (/app/node_modules/mongoose/lib/index.js:321:15)
2019-09-02T06:28:59.763848+00:00 app[web.1]: at Object.<anonymous> (/app/index.js:24:10)
2019-09-02T06:28:59.763850+00:00 app[web.1]: at Module._compile (internal/modules/cjs/loader.js:701:30)
2019-09-02T06:28:59.763852+00:00 app[web.1]: at Object.Module._extensions..js (internal/modules/cjs/loader.js:712:10)
2019-09-02T06:28:59.763854+00:00 app[web.1]: at Module.load (internal/modules/cjs/loader.js:600:32)
And the second one is this
2019-09-02T08:49:22.115492+00:00 app[web.1]: { MongoNetworkError: failed to connect to server [productionproj-shard-00-00-qfouv.mongodb.net:27017] on first connect [MongoNetworkError: connection 5 to productionproj-shard-00-00-qfouv.mongodb.net:27017 closed]
So on...... as same as above
Here is my mongodb production url i've been added on heroku config vars
mongodb+srv://nansProdDeploy:nansProdDeploy#productionproj-qfouv.mongodb.net/test?retryWrites=true&w=majority
It's all about whitelisting the correct ip address. When we put our application on heroku we must whitelist the ip by clicking [ Allow Access From Anywhere ] button and then click ok your ip will be 0.0.0.0/0 this ip will allow to access your deployed heroku application. When you are using your application locally at that point of you have to choose [ Add Current Ip Address ] to access your application locally

webpack exception when using express middleware router

I have a simple webpack with react hotloader & express setup and working. I'm trying to add an external node module that will register a sub router for some services. For some reason, doing so causes a strange exception (see below).
var path = require('path');
var express = require('express');
var webpack = require('webpack');
var config = require('./webpack.config');
var app = express();
var router = express.Router();
var mod = require("my-module");
mod.registerServices(router); // <-- adds routes to the router
app.use("/api/v1*", router); // <-- This line causes the error
var compiler = webpack(config);
app.use(require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath: config.output.publicPath,
stats: {
colors: true
}
}));
app.use(require('webpack-hot-middleware')(compiler));
app.get('/*', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(3000, 'localhost', function(err) {
if (err) {
console.log(err);
return;
}
console.log('Listening at http://localhost:3000');
});
The Exception:
$ node server.js
/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51
throw new Error('locals[0] does not appear to be a `module` object with Hot Module ' + 'replacement API enabled. You should disable react-transform-hmr in ' + 'production by using `env` section in Babel configuration. See the ' + 'example in README: https://github.com/gaearon/react-transform-hmr');
^
Error: locals[0] does not appear to be a `module` object with Hot Module replacement API enabled. You should disable react-transform-hmr in production by using `env` section in Babel configuration. See the example in README: https://github.com/gaearon/react-transform-hmr
at Object.proxyReactComponents [as default] (/Users/bmonro/Documents/Code/nui-redux/node_modules/react-transform-hmr/lib/index.js:51:11)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/components/simple.js:25:60)
at Module._compile (module.js:434:26)
at Object.Module._extensions..js (module.js:452:10)
at Module.load (module.js:355:32)
at Function.Module._load (module.js:310:12)
at Module.require (module.js:365:17)
at require (module.js:384:17)
at Object.<anonymous> (/Users/bmonro/Documents/Code/nui-redux/src/ext/nui-company-admin/lib/CompanyLocation/containers/CompanyLocationPage.js:13:25)
at Module._compile (module.js:434:26)
UPDATE
Turns out that removing this from .babelrc where I have some react transforms enabled and subsequently removing all of the web pack hotloader plugins & middleware gets the router working again.
{
"transform": "react-transform-hmr",
"imports": ["react"],
"locals": ["module"]
}
Try this solution: don't use babel-plugin-react-transform in .babelrc, use config in webpack.config.js
module: {
loaders: [
{
test: /\.(js|jsx)$/,
loader: 'babel',
include: path.join(__dirname, 'src'),
query: {
plugins: [
["react-transform", {
transforms: [{
transform: "react-transform-hmr",
imports: ["react"],
locals: ["module"]
}]
}]
]
}
}
]
}
Details:
https://github.com/gaearon/babel-plugin-react-transform/issues/62
https://github.com/gaearon/react-transform-hmr/issues/5

Gulp Watch - gulp-nodemon - App Crashed

I'm trying to set up Gulp to watch 1 thing: server's source. Upon source update, the server node script will start over & client browser will refresh.
I believe I need gulp-nodemon for the server, while browser-sync for the client.
The server's script is executed by: node src\babel.js
The script works when ran that way, but fails through my config for Gulp.
Is there something I am doing wrong?
This is my task script:
var gulp = require('gulp');
var browserSync = require('browser-sync');
var nodemon = require('gulp-nodemon');
gulp.task('default', ['watchServer', 'watchClient']);
gulp.task('watchServer', function() {
gulp.watch('src/**', function () {
nodemon({ // called upon update
script: 'src/babel.js', // I have tried both / & \\
})
});
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
})
});
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: '████████',
port: 80,
ui: false,
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});
Log:
> gulp
[02:28:04] Using gulpfile B:\Test Server\gulpfile.js
[02:28:04] Starting 'watchServer'...
[02:28:04] Finished 'watchServer' after 19 ms
[02:28:04] Starting 'watchClient'...
[02:28:04] Finished 'watchClient' after 27 ms
[02:28:04] Starting 'default'...
[02:28:04] Finished 'default' after 9.66 Ξs
[02:28:04] [nodemon] 1.7.1
[02:28:04] [nodemon] to restart at any time, enter `rs`
[02:28:04] [nodemon] watching: *.*
[02:28:04] [nodemon] starting `node src\babel.js`
[BS] Access URLs:
-----------------------------------
Local: http://localhost:80
External: http://████████:80
-----------------------------------
[BS] Serving files from: src
[BS] Watching files...
events.js:141
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE :::80
at Object.exports._errnoException (util.js:837:11)
at exports._exceptionWithHostPort (util.js:860:20)
at Server._listen2 (net.js:1231:14)
at listen (net.js:1267:10)
at Server.listen (net.js:1363:5)
at B:/Test Server/src/app/app.jsx:17:7
at Object.<anonymous> (B:/Test Server/src/app/app.jsx:41:2)
at Module._compile (module.js:434:26)
at normalLoader (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:199:5)
at Object.require.extensions.(anonymous function) [as .jsx] (B:\Test Server\node_modules\babel-core\lib\api\register\node.js:216:7)
[02:28:05] [nodemon] app crashed - waiting for file changes before starting...
You don't need to watch the server file with gulp since nodemon will automatically restart when it changes, try something like this in your config
gulp.task('watchServer', function() {
// remove the gulp.watch entry
nodemon({ // called on start
script: 'src/babel.js', // I have tried both / & \\
ext: 'js',
watch: ['src/babel.js']
})
});
There also seems to be something else running on port 80 (this is the default port for apache) so it might help to change the port browsersync is running on to something like 4000
If your node server is running on let's say port 3000 you will need to proxy it with browsersync for example.
gulp.task('watchClient', function() {
browserSync({
open: 'external',
host: '████████',
proxy: '[YOURHOST]:3000'
port: 4000,
ui: false,
// this entry will most likely need to be removed
// if you are using something like express as a static server
server: {
// We're serving the src folder as well
// for sass sourcemap linking
baseDir: ['src']
},
files: [
'src/**'
]
});
});

Resources