Unable to track the issue this.stack.push(layer); in node.js - mysql

this is my code
usercontroller:-
const {hashSync,genSaltSync}=require('bcrypt');
const {create}=require('./user.service');
module.exports={
createUser:(req,res)=>{
const body=req.body;
const salt=genSaltSync(10);
body.password=hashSync(body.password,salt);
create(body,(error,results)=>{
if(error){
return res.status(500).json(
{
success:0,
message : "Database connection error"
}
);
}
return res.status(200).json({
status:200,
data:results
});
})
}
}
userservice:-
const pool=require("../config/database")
module.exports={
create: (data,callback)=>{
pool.query(
`insert into registration(firstName,lastName,gender,email,password,number)
values(?,?,?,?,?,?)`,
[
data.first_name,
data.last_name,
data.gender,
data.email,
data.password,
data.number
],
(error,results,fields) =>
{
if(error)
{
return callback(error);
}
else{
return callback(null,results);
}
}
);
}
}
userrouter:-
const {createUser} = require("../users/user.controller")
const {createUser}=require("./user.controller")
const router=require("express").Router;
router.post("/",createUser);
module.exports=router;
app.js
require("dotenv").config();
const express = require("express")
const app=express();
const userrouter=require('./users/user.router')
app.use("/api/users",userrouter);
app.listen(process.env.APP_PORT,()=>{
console.log("server up and running")
});
.env
APP_PORT=3000
DB_PORT=3306
DB_HOST=localhost
DB_USER=root
DB_PASSWORD=divyanshu123
MYSQL_DB=test
i am not able to run it getting error:-
[nodemon] 2.0.4
[nodemon] to restart at any time, enter rs
[nodemon] watching path(s): .
[nodemon] watching extensions: js,mjs,json
[nodemon] starting node app.js
C:\Users\Divyanshu Thakur\Desktop\Jwt\node_modules\express\lib\router\index.js:502
this.stack.push(layer);
^
TypeError: Cannot read property 'push' of undefined
at Function.route (C:\Users\Divyanshu Thakur\Desktop\Jwt\node_modules\express\lib\router\index.js:502:14)
at Function.proto. [as post] (C:\Users\Divyanshu Thakur\Desktop\Jwt\node_modules\express\lib\router\index.js:509:22)
at Object. (C:\Users\Divyanshu Thakur\Desktop\Jwt\users\user.router.js:4:8)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object. (C:\Users\Divyanshu Thakur\Desktop\Jwt\app.js:4:18)
[nodemon] app crashed - waiting for file changes before starting...

Change this:
const router=require("express").Router;
to this:
const router=require("express").Router();
You have to actually call the factory function to create a new router. Your problem then occurs when you try to do:
router.post("/",createUser);
or:
app.use("/api/users",userrouter);
But, your object isn't actually a router.

Not sure if this is the source of your issue but this seems rather problematic:
const { createUser } = require("../users/user.controller")
const { createUser } = require("./user.controller")
That's from the userRouter file.

Related

Error: connect ETIMEDOUT, how to solve it? using Node.js and MySQL2

I used Node.js and MySQL2. Working on MySQL workbench. Created virtual DB using Railway workbench. Schemas and tables are created. But showing `ETIMEDOUT error in the VS code's terminal when i try to run node index.js. What can i do?
db.js:
import mysql2 from 'mysql2';
export const db = mysql2.createConnection({
host: 'containers-us-west-174.railway.app',
user: 'user',
password: 'password',
database: 'railway'
})
index.js:
import express from 'express';
import authRoutes from './routes/auth.js';
import userRoutes from './routes/users.js';
import postRoutes from './routes/posts.js';
import dotenv from 'dotenv';
import cookieParser from 'cookie-parser';
import multer from 'multer';
dotenv.config();
const app = express();
app.use(express.json());
app.use(cookieParser());
const storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, '../client/public/upload');
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' + file.originalname);
}
})
const upload = multer({ storage: storage })
app.post('/api/upload', upload.single('file'), function (req, res) {
const file = req.file;
res.status(200).json(file?.filename)
});
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
app.use('/api/posts', postRoutes);
app.listen(8800, () => {
console.log('Connected wih backend!');
})
In my VS Code Terminal it is showing this error:
Connected wih backend!
node:events:505
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT
at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:189:17)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7)
Emitted 'error' event on Connection instance at:
at Connection._notifyError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:236:12)
at Connection._handleFatalError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:167:10)
at Connection._handleNetworkError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:180:10)
at Connection._handleTimeoutError (I:\EMON\Web-Development\FINALE\timeless-blog-f\api\node_modules\mysql2\lib\connection.js:193:10)
at listOnTimeout (node:internal/timers:559:17)
at processTimers (node:internal/timers:502:7) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
I was trying to deploting in railway. I'm using MySQL workbench.
In Railway deployment logs this error shows:
> api#1.0.0 start
> node index.js
node:internal/modules/cjs/loader:1239
return process.dlopen(module, path.toNamespacedPath(filename));
^
Error: /app/node_modules/bcrypt/lib/binding/napi-v3/bcrypt_lib.node: invalid ELF header
at Object.Module._extensions..node (node:internal/modules/cjs/loader:1239:18)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12)
at Module.require (node:internal/modules/cjs/loader:1057:19)
at require (node:internal/modules/cjs/helpers:103:18)
at Object.<anonymous> (/app/node_modules/bcrypt/bcrypt.js:6:16)
at Module._compile (node:internal/modules/cjs/loader:1155:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1209:10)
at Module.load (node:internal/modules/cjs/loader:1033:32)
at Function.Module._load (node:internal/modules/cjs/loader:868:12) {
code: 'ERR_DLOPEN_FAILED'
}
npm WARN config production Use `--omit=dev` instead.
And deployment crashed!
Any solution?

'argument hostname required' vhost

Having a weird issue with express vhost inside AWS. Every time I deploy I get an error in my EB log saying:
TypeError: argument hostname is required
at vhost (/var/app/current/node_modules/vhost/index.js:39:11)
at Object.<anonymous> (/var/app/current/app.js:554:9)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:60:12)
at internal/main/run_main_module.js:17:47
/var/app/current/node_modules/vhost/index.js:39
throw new TypeError('argument hostname is required')
^
If I have a look at the vhost module, index.js: line 36 we have the following:
function vhost(hostname, handle) {
if (!hostname) {
throw new TypeError('argument hostname is required')
}
if (!handle) {
throw new TypeError('argument handle is required')
}
if (typeof handle !== 'function') {
throw new TypeError('argument handle must be a function')
}
Not even any typechecking or anything on hostname like there is for handle, just checking if the value is passed in. Which it clearly is in the following code:
const app = express();
const register_app = express();
const nonadmin_app = express();
register_app.use(express.static(path.resolve(__dirname, './build/register')));
nonadmin_app.use(express.static(path.resolve(__dirname, './build/nonadmin')));
app.use(vhost('register.<eb-dev-url>.elasticbeanstalk.com/', register_app))
app.use(vhost('nonadmin.<eb-dev-url>.elasticbeanstalk.com/', nonadmin_app))
app.use(vhost('api.<eb-dev-url>.elasticbeanstalk.com/', api))
register_app.get('/register', (req, res) => {
res.sendFile(path.resolve(__dirname, './build/register', 'index.html'));
})
nonadmin_app.get('/nonadmin', (req, res) => {
res.sendFile(path.resolve(__dirname, './build/nonadmin', 'index.html'));
})
I'm not convinced this is a problem with vhost because when using register.localhost, nonadmin.localhost, or api.localhost when running this app locally using nodemon it works just fine. I also tried deploying with a .localhost suffix and still did not work.
Is there something I am missing in terms of AWS hostname config?
The answer was trailing slashes in the hostname argument.
Will raise a bug request.

How to connect my application with MySQL database as a service on oracle cloud infrastructure?

I want to connect my web application which is in development phase to the MySQL database as a service in the oracle cloud infrastructure. Currently, I have been able to configure the MySQL database as a service and I am able to connect to it through the server CLI as well as from Workbench installed on my remote pc and create and query databases from the CLI. The database changes (new db, table creation, updation) are represented in the Workbench as well as any other remote environment that I use to connect to the the database service.
So I believe the database has been correctly deployed. The problem that I am facing right now when I try to connect to the MySQL DBS from within any of my applications is that I get some connection timeout error and I am not able to connect to it from within my code. I am new to this and I am not able to understand the reason behind this. I have spent quite a few days to figure out the problem. Any help would be greatly appreciated.
I am using Sequelize ORM and mysql2
Below is my config.json file for connecting with the remotely deployed database:
{
"development": {
"username": "johndoe",
"host": "10.0.1.3",
"dialect": "mysql",
"password": "Oraclecloud1#",
"database": "test"
},
host is where MySQL is running on the remote 130.61.183.23 instance address.
Server.js file for setting up the local node js server on my machine to run the application
const express=require('express')
const app=express()
app.use(express.json())
app.use(express.urlencoded({extended:true}))
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
res.header('Access-Control-Allow-Methods', "POST, GET, PUT, DELETE, OPTIONS");
next();
});
var models=require('./models')
models.sequelize.sync().then(function(){
console.log('Database looks fine')
}).catch(function(err){
console.log(err,'Something went wrong with the db')
})
require('./routers/index')(app)
port=process.env.PORT || 3003
app.listen(port,console.log('server up'))
Index.js file in models
'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/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);
}
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;
Below is the timeout error that I get
ConnectionError [SequelizeConnectionError]: connect ETIMEDOUT at ConnectionManager.connect (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\mysql\connection-manager.js:126:17)
at processTicksAndRejections (internal/process/task_queues.js:93:5)
at async ConnectionManager._connect (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:318:24)
at async D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:250:32
at async ConnectionManager.getConnection (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\connection-manager.js:280:7)
at async D:\Notes\Node\servertest\node_modules\sequelize\lib\sequelize.js:613:26
at async MySQLQueryInterface.createTable (D:\Notes\Node\servertest\node_modules\sequelize\lib\dialects\abstract\query-interface.js:225:12)
at async Function.sync (D:\Notes\Node\servertest\node_modules\sequelize\lib\model.js:1300:5)
at async Sequelize.sync (D:\Notes\Node\servertest\node_modules\sequelize\lib\sequelize.js:793:35) {
parent: Error: connect ETIMEDOUT
at Connection._handleTimeoutError (D:\Notes\Node\servertest\node_modules\mysql2\lib\connection.js:178:17)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
},
original: Error: connect ETIMEDOUT
at Connection._handleTimeoutError (D:\Notes\Node\servertest\node_modules\mysql2\lib\connection.js:178:17)
at listOnTimeout (internal/timers.js:554:17)
at processTimers (internal/timers.js:497:7) {
errorno: 'ETIMEDOUT',
code: 'ETIMEDOUT',
syscall: 'connect',
fatal: true
}
} Something went wrong with the db
Looking into this it seems that several possible things could be happening including that your DB is not running or that your firewall is not allowing for access. One other thing I've seen includes adding a pool option to your configuration - SequelizeConnectionError in Node.js application

how to use mysql in node.js all app files?

Hello mates, first, I hope everyone is in good health.
Sorry if this question is a little confuse, but i'm trying creating a API/webservice that works with MySql, so I have
in root (/) the file bd.js with the connection
bd.js:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : '',
database : 'skey-9'
});
connection.connect(function(err) {
if (err) throw err;
});
module.exports = connection;
then i add to /app.js and have the routes of diferente directories
app.js:
const express = require('express');
const app = express();
const morgan = require('morgan');
const bodyParser = require('body-parser');
const db = require('./bd');
const productRoutes = require('./api/routes/products');
const orderRoutes = require('./api/routes/order');
app.use(morgan('dev'));
app.use(bodyParser.urlencoded({extended: false}))
app.use(bodyParser.json());
//Routes
app.use('/products', productRoutes);
app.use('/orders', orderRoutes);
in the final i'm trying to query a Select in /routes/products.js
products.js:
const express = require('express');
const router = express.Router();
var db = require('./../bd');
con.connect((err) => {
if(err){
console.log('Error connecting to Db');
return;
}
console.log('Connection established');
});
con.query('SELECT * FROM teste', (err,rows) => {
if(err) throw err;
console.log('Data received from Db:');
console.log(rows);
});
router.get('/', (req, res, next) => {
res.status(200).json({
message: 'handling GET requests to / products',
query: rows
});
});
module.exports = router;
but i'm getting a error i already tried to "playing" with the bd files.
the error:
C:\NODE\node-rest\server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:957:15)
at Function.Module._load (internal/modules/cjs/loader.js:840:27)
at Module.require (internal/modules/cjs/loader.js:1019:19)
at require (internal/modules/cjs/helpers.js:77:18)
at Object.<anonymous> (C:\NODE\node-rest\api\routes\products.js:3:10)
at Module._compile (internal/modules/cjs/loader.js:1133:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:10)
at Module.load (internal/modules/cjs/loader.js:977:32)
at Function.Module._load (internal/modules/cjs/loader.js:877:14)
at Module.require (internal/modules/cjs/loader.js:1019:19) {
code: 'MODULE_NOT_FOUND',
requireStack: [
'C:\\NODE\\node-rest\\api\\routes\\products.js',
'C:\\NODE\\node-rest\\app.js',
'C:\\NODE\\node-rest\\server.js'
]
My question is how can i do a "global" mysql connection to all the app I'm creating.
soo i have 2 subpath's, and for some reason i had to change
var db = require('./../bd'); "
to
var db = require('..\\..\\bd'); "
forget this dont resolve my problem, we have to run a connection to all the router's?

Syntax Error unexpected identifier for bcrypt function. Where am I going wrong?

Developing a login authenticator using node, express, mysql, brcpt etc. I got stuck here when the bcrypt.compare is giving a syntax error in the console which I am unable to debug.
app.post('/login', async (req, res) => {
const email = req.body.email
const password = req.body.password
if (email && password) {
con.query("SELECT * FROM users WHERE email = ? AND password = ?", [email, password], function(err, results, fields){
if (await bcrypt.compare(password, hashedPassword, (err, isMatch) => {
if (err) throw err
callback(null, isMatch)
}) && results.length > 0) {
request.session.loggedin = true
request.session.email = email
response.redirect('/')
} else {
response.send('Incorrect Username and/or Password!')
}
response.end()
})
} else {
response.send('Please enter Username and Password!')
response.end()
}
})
Given above is the login handle and route for the process.
Here is the error thrown out to the terminal:
[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
/Users/vaidiklapalikar/Desktop/current project/server.js:51
if (await bcrypt.compare(password, hashedPassword, (err, isMatch) => {
^^^^^^
SyntaxError: Unexpected identifier
at wrapSafe (internal/modules/cjs/loader.js:1067:16)
at Module._compile (internal/modules/cjs/loader.js:1115:27)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1171:10)
at Module.load (internal/modules/cjs/loader.js:1000:32)
at Function.Module._load (internal/modules/cjs/loader.js:899:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
[nodemon] app crashed - waiting for file changes before starting...
Please help me out! Thanks in advance!