Why is Knex not able to insert into mysql? - mysql

I am trying to insert a row of values into MySQL database using Knex but I am getting a weird error. The table and database exist and the fetch API works perfectly but I am not able to insert values using sifnUp route.
const db= knex ({
client: 'mysql2',
connection: {
host: '127.0.0.1',
port: 3306,
user: 'root',
password: '',
database: 'transaction_app'
}
});
app.get('/', (req, res) => {
res.send('App is running')
});
app.post('/signUp', (req, res,db) => {
const {name, email, mobile, password}=req.body;
const hash=bcrypt.hashSync(password, 10);
db('users')
.insert({
name: name,
email: email,
mobile: mobile,
password: hash
})
.then(data=>{
res.send(data);
})
.catch(err=>{
res.send(err);
})
});
app.get('/fetch',(req,res)=>{
db.select('*').from('users')
.then(data=>{
res.send(data);
})
.catch(err=>{
res.send(err);
})
})
app.listen(3000, () =>{
console.log('Server started on port 3000');
});
The error that is consoled is this
Server started on port 3000
users
TypeError: Cannot read properties of undefined (reading 'insert')
at D:\Documents\Atoa Assignment\server.js:35:3
at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (D:\Documents\Atoa Assignment\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (D:\Documents\Atoa Assignment\node_modules\express\lib\router\layer.js:95:5)
at D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:284:15
at Function.process_params (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:346:12)
at next (D:\Documents\Atoa Assignment\node_modules\express\lib\router\index.js:280:10)
at cors (D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:188:7) at D:\Documents\Atoa Assignment\node_modules\cors\lib\index.js:224:17
This is the Postman Screenshot.

Your error:
app.post('/signUp', (req, res,db) => {
const {name, email, mobile, password}
The third parameter is the express next, not db.
Inside the route you assign next() to db. (req,res,"db")
Must be (req,res, next).
When you call db.insert it is not referring of the top of your code
const db= knex ({
So you dont db.insert but next.insert (which obviously does not exist).
As you are not using the next handler of express, simply delete db in (req,res,db) and it should work.
Remember the scopes of variables in Javascript.
An Example

Related

How to connect not to local MySQL db (PHPMyAdmin) by using React.js?

I am pretty new at Node.js, and I have existing database uploaded to Dreamhost, which has database PhpMyAdmin. I have created new React application, and by using my server folder I am trying to connect to that database. I am using Windows 10, and I run at http://127.0.0.1:5000/. This is my code:
const express = require("express");
const bodyParser = require("body-parser");
const mysql = require("mysql");
const app = express()
const port = process.env.PORT || 5000
app.use(bodyParser.urlencoded({ extended: false }))
app.use(bodyParser.json())
// MySQL
const pool = mysql.createPool({
connectionLimit: 10,
user: "root",
host: '127.0.0.1',
password: "password",
database: "testdb_org"
})
// Get all info
app.get('/', (req, res) => {
pool.getConnection((err, connection) => {
res.send('TEST '+ JSON.stringify(err))
/*if (err) throw err
console.log(`Connected as id ${connection.threadId}`)
connection.query('SELECT * from users', (err, rows) => {
connection.release() // Return the connection to pool
if (!err) {
res.send(rows)
} else {
console.log(err)
}
})*/
})
})
app.listen(port, () => console.log(`Listen on port ${port}`))
res.send gives me following error:
{"code":"ER_ACCESS_DENIED_ERROR","errno":1045,"sqlMessage":"Access denied for user 'root'#'localhost' (using password: YES)","sqlState":"28000","fatal":true}
And when I open comment brackets it gives me following console error:
if (err) throw err
^
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
--------------------
at Protocol._enqueue (C:\Users\*\Documents\project\server\node_modules\mysql\lib\protocol\Protocol.js:144:48)
at Protocol.handshake (C:\Users\*\Documents\project\server\node_modules\mysql\lib\protocol\Protocol.js:51:23)
at PoolConnection.connect (C:\Users\*\Documents\project\server\node_modules\mysql\lib\Connection.js:116:18)
at Pool.getConnection (C:\Users\*\Documents\project\server\node_modules\mysql\lib\Pool.js:48:16)
at C:\Users\*\Documents\project\server\app.js:24:10
at Layer.handle [as handle_request] (C:\Users\*\Documents\project\server\node_modules\express\lib\router\layer.js:95:5)
at next (C:\Users\*\Documents\project\server\node_modules\express\lib\router\route.js:144:13)
at Route.dispatch (C:\Users\*\Documents\project\server\node_modules\express\lib\router\route.js:114:3)
at Layer.handle [as handle_request] (C:\Users\*\Documents\project\server\node_modules\express\lib\router\layer.js:95:5)
at C:\Users\*\Documents\project\server\node_modules\express\lib\router\index.js:284:15 {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
Ok, the problem that it's not possible with online database and localhost of React.js. For connection I had to download .sql database, insert and run it locally with XAMPP control panel.

Connected to the database but through error when I try to insert into database table

I am not able to insert data to the database. There is no issues connected to the database but when I try to insert into table, It through an error.
Error: Cannot enqueue Query after fatal error.
How can I solve this problem? Anyone facing same problem?
const { redirect } = require("express/lib/response");
const mysql = require('mysql')
let con = mysql.createConnection({
host: process.env.db_host,
database: process.env.db_database,
username: process.env.db_username,
password: process.env.db_password,
port: process.env.db_port
});
con.connect(err=>{
{err===true? console.log(err): console.log("DB connected Successfully!!");;}
})
// Home Page
exports.index = (req,res)=>{
res.render('../views/index', {btnName: 'Save' })
console.log("You are in home page!");
}
// // Add User
// exports.addUser = (req,res)=>{
// res.render('adduser')
// }
exports.adduserpost = (req,res)=>{
const {fname, mname, lname, email, phone} = req.body; //store value from adduser
// console.log({fname, mname, lname, email, phone});
let sql = 'INSERT INTO user_info (fname, mname, lname, email, phone) VALUES (?,?,?,?,?)';
con.query(sql,[fname, mname, lname, email, phone],
(err,result)=>{
if(!err) console.log(result);
else console.log( err);
})
Through Error like this.
Server connected successfully!!
DB connected Successfully!!
Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (F:\Project\User_Information_System_v2\node_modules\mysql\lib\protocol\Protocol.js:212:16)
at Protocol._enqueue (F:\Project\User_Information_System_v2\node_modules\mysql\lib\protocol\Protocol.js:138:13)
at Connection.query (F:\Project\User_Information_System_v2\node_modules\mysql\lib\Connection.js:198:25)
at exports.adduserpost (F:\Project\User_Information_System_v2\server\controller\userController.js:53:5)
at Layer.handle [as handle_request] (F:\Project\User_Information_System_v2\node_modules\express\lib\router\layer.js:95:5)
at next (F:\Project\User_Information_System_v2\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (F:\Project\User_Information_System_v2\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (F:\Project\User_Information_System_v2\node_modules\express\lib\router\layer.js:95:5)
at F:\Project\User_Information_System_v2\node_modules\express\lib\router\index.js:281:22
at Function.process_params (F:\Project\User_Information_System_v2\node_modules\express\lib\router\index.js:341:12) {
code: 'PROTOCOL_ENQUEUE_AFTER_FATAL_ERROR',
fatal: false
}
You should change your connect error checking condition.
By using err===true the message DB connected Successfully!! will be displayed also if the err is present as an object.
Try to change your code like this and see if it logs any error messages:
con.connect(err=>{
if(err) {
console.log(err);
process.exit(1);
}
console.log("DB connected Successfully!!")
})

How to handle MySQLStore connection error?

I'm using NodeJS with express. I'm store the sessions to a MySQLStore (express-mysql-session)
My question is how can i handle connection error? When it can't connect i want to render a page to the users instead of the "Error: connect ECONNREFUSED 127.0.0.1:3306 at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1137:16) ....." message.
My code:
const MySQLStore = require('express-mysql-session')(session);
(....)
app.use(session({
secret: 'something',
resave: false,
saveUninitialized: false,
store: new MySQLStore({
host: something,
user: something,
password: something,
database: something
}),
cookie: {
maxAge: 7 * 24 * 60 * 60 * 1000
}
}));
With the simple mysqljs i could do it easily because when i use connection.query there is an (error, result) => { ... } where i can handle error but at this MySQLStore i have no clue how to handle connection error.
Solved it, an Express error handler middleware can catch this error too.
Just paste this by the end of the application just before app.listen.
app.use((error, req, res, next) => {
res.status(error.status || 500).render('error', {
msg: 'Please check back later!'
});
});
Be aware that the next parameter needed even if we don't use it because error-handling functions have four parameters in express. If you delete it, it will not work.

How to fetch data from MySQL database with Node

I'm new to react, developing a recipe-app and I got a problem while displaying the data from MySQL database. The connection was created successfully, however, I'm not sure about how to reach the data. When I run node server.js in my terminal, I get "connected", When I visit the localhost:8080/users, I get "This site can't be reached" message and in my terminal:
`events.js:187
throw er; // Unhandled 'error' event
^
Error: Cannot enqueue Handshake after already enqueuing a Handshake.`
I'm a little stuck here. Anyone knows a solution or direct me a little bit? Thank you so much!
Server.js
const express = require('express');
const app = express();
const PORT = 8080;
const mysql = require('mysql');
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => {
if (err) throw err;
console.log('Connected!');
});
//creating route for the app
app.get('/users', (req, res) => {
connection.connect();
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
res.send(JSON.stringify(rows));
} else {
console.log('Error while performing Query.');
}
});
connection.end();
});
//making server listen to request
app.listen(PORT, () => {
console.log(`Server running at : http://localhost:${PORT}/`);
});
You're trying to reconnect to mysql after the connection has been established.
See my comments on the code below
const connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'recipe_app'
});
connection.connect((err) => { // This creates the connection
if (err) throw err;
console.log('Connected!');
});
And when you're trying to resolve your GET routes, you're trying to connect again
//creating route for the app
app.get('/users', (req, res) => {
connection.connect(); // reconnect here
Since you're using the default connection method, trying to connect to an already established connection will cause the driver to throw a Handshake error.
If you want to re-use the connection, store it in a variable and then re-use it in other part of your code.
If you want to manage multiple connections instead, I suggest you to look at createPool instead.
Try removing the connection.connect() and connection.end() from app.get

Access Body Param NodeJS Express

I have a route
router.post('/api/getSessionTimeOut', apiController.getSessionTimeOut);
This is in my controller
function getSessionTimeOut(req, res) {
res.send(req.body.session); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
var options =
{
method: 'POST',
url: 'http://api/json',
body:
{
id: 1,
method: 'get',
params: [
{
url: '/cli/global/system/admin/setting'
}
],
session: req.params.session
},
json: true
};
request(options, function (error, response, body) {
if (error) throw new Error(error);
console.log(body, response);
res.send(response.result);
});
};
After making a POST to the route with session as body via Postman
I kept getting
Red alert! Red alert!: TypeError: Cannot read property 'session' of undefined
at getSessionTimeOut (/Users/doe/Desktop/express-app/controllers/api.js:50:23) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/route.js:137:13) at Route.dispatch (/Users/doe/Desktop/express-app/node_modules/express/lib/router/route.js:112:3) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:281:22 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at Function.handle (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:174:3) at router (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:47:12) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:317:13) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at serveStatic (/Users/doe/Desktop/express-app/node_modules/serve-static/index.js:75:16) at Layer.handle [as handle_request] (/Users/doe/Desktop/express-app/node_modules/express/lib/router/layer.js:95:5) at trim_prefix (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:317:13) at /Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:284:7 at Function.process_params (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:335:12) at next (/Users/doe/Desktop/express-app/node_modules/express/lib/router/index.js:275:10) at expressInit (/Users/doe/Desktop/express-app/node_modules/express/lib/middleware/init.js:40:5)
index.js
import express from 'express'
import favicon from 'serve-favicon'
import path from 'path'
import bodyParser from 'body-parser'
// Controllers
import apiController from './controllers/api'
const router = express.Router();
const app = express();
const PORT = 3000;
//For public folder
app.use(express.static('public'))
app.use(router)
app.use('/images',express.static('images'))
app.use(favicon(path.join(__dirname,'public','favicon.ico')))
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
router.get('/', (req,res) => {
res.send('Welcome to the backend provisioning daemon to program FortiManager')
});
// app.use( express.json());
app.use(express.urlencoded({extended: true}))
app.set('trust proxy', 'loopback');
//Fortinet
router.post('/api/getSessionTimeOut', apiController.getSessionTimeOut);
router.post('/api/login', apiController.login);
//Error handling function
app.use((err,req,res,next) => {
console.error(err.stack)
res.status(500).send(`Red alert! Red alert!: ${err.stack}`)
});
// app listen
app.listen(PORT, () => {
console.log(`Your server is running on ${PORT}`)
}
);
Try moving
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true }));
right after
const app = express();
Why, because you need to use/register middlewares on your server/app before registering any route on your server. This will make sure that every request coming to the registered route is first passed through body-parsers and will let the body-parsers to do the construct the request data in its specified data structure or format.
Hope that helps
Thanks