express-http-context getting lost after calling mysql - mysql

Need your help. I am trying to implement global request id for my nodejs application. For that I am using express-http-context lib to set request id. But it's not working as expected when my code access data from mysql database. Seems like there is a compatibility issue in cls used by express-http-context and mysql library.
Sample code and the output is provided below:
const app = require('express')();
const httpContext = require('express-http-context');
const mysql = require('mysql');
const { INTERNAL_SERVER_ERROR, OK, NOT_FOUND } = require('http-status-codes');
const http = require('http');
const uuidv4 = require('uuid/v4');
const pool = mysql.createPool({
host: '127.0.0.1',
port: 3306,
user: 'root',
password: 'Redhat#123',
database: 'user',
connectionLimit: 10,
});
pool.query('SELECT 1 + 1 AS solution', (error) => {
if (error) {
console.log('Unable to connect to MySQL:- ', error.message);
process.exit(1);
}
console.log('MySQL PING is Working');
});
app.use(httpContext.middleware);
app.use((req, res, next) => {
httpContext.set('requestId', uuidv4());
console.log('request Id set is: ', httpContext.get('requestId'));
next();
});
const getUserDetailsRepository = (userId, callback) => {
console.log('inside getuserDetails repository for request id: ', httpContext.get('requestId'));
pool.getConnection((connectionError, connection) => {
if (connectionError) {
console.log('got ConnError getuserDetails repository for request id: ', httpContext.get('requestId'));
callback(connectionError);
} else {
const query = 'SELECT * from user where id = ?';
connection.query(query, [userId], (queryError, results) => {
connection.release();
if (queryError) {
console.log('got queryError getuserDetails repository for request id: ', httpContext.get('requestId'), queryError.message);
callback(queryError);
} else {
console.log('Got response inside getuserDetails repository for request id: ', httpContext.get('requestId'));
callback(null, results);
}
});
}
});
};
const userGetDetails = (req, res, next) => {
const { userId } = req.params;
console.log('inside getUserDetails controller for request id: ', httpContext.get('requestId'));
getUserDetailsRepository(userId, (error, result) => {
if (error) {
console.log('got Error in getuserDetails controller for request id: ', httpContext.get('requestId'))
res.sendStatus(INTERNAL_SERVER_ERROR);
} else if (result) {
console.log('Got response inside getuserDetails repository for request id: ', httpContext.get('requestId'));
res.status(OK).json(result);
} else {
res.sendStatus(NOT_FOUND);
}
});
};
app.get('/user/:userId', userGetDetails);
const server = http.createServer(app);
server.listen(3000, () => console.log('Http server started listening on port'));
Output:
Http server started listening on port
MySQL PING is Working
request Id set is: ea4895ab-8003-4d28-99aa-b03af7027ae8
inside getUserDetails controller for request id: ea4895ab-8003-4d28-99aa-b03af7027ae8
inside getuserDetails repository for request id: ea4895ab-8003-4d28-99aa-b03af7027ae8
Got response inside getuserDetails repository for request id: undefined
Got response inside getuserDetails repository for request id: undefined

i hope this solution solve your problem and save many hours for anyone that have this problem
you can just use bindEmitter to solve the problem
app.use((req, res, next) => {
httpContext.ns.bindEmitter(req);
httpContext.ns.bindEmitter(res);
var requestId = req.headers["x-request-id"] || uuidv4();
httpContext.set("requestId", requestId);
console.log('request Id set is: ', httpContext.get('requestId'));
next();
});

Related

Why I'm always getting an Internal Server Error (code 500) after making a request to BackEnd

I'm having a little trouble with my site and I can't understand what is happening.
First of all I have to say that I was NOT having this behavior when developing on localhost, but now that my site is close to be completed I think that uploading my code to a hosting service and make some tests there would be a good idea.
The issue is that when I make a request to the database, most of the times the site keeps in an eternal loading state, until the error code 500: Internal Server Error appears (I said "most of the times" because it works nice sometime, but normally it remains in a pending state).
Given the fact that SOME TIMES the request work nice, makes me think that the issue is not on the server.js file (where I defined the endpoints), and also is not on my controllers files (where I have some logic and the requests itself).
I'll leave here some pics as example of what is happening but if you need some extra info just tell me:
A simple login example, I just fill the fields and send the request
And here you can see how the request remain as pending
Until it fails
EDIT: I'm using package Mysql2 to connect to the DB, and I was reading that this behavior may be because a bad use of connections (and I'm reading about "pools", but I'm kinda lost tbh)
Here is the connection file:
require("dotenv").config();
const mysql = require("mysql2");
const db = mysql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
waitForConnections: true,
});
const connection = async () => {
db.connect((err) => {
if (err) throw err;
console.log("Successfully connected");
})
}
exports.db = db;
exports.connection = connection;
The first call to the DB (just to check the connection)
connection().then(() => {
app.listen(port, () => {
console.log(`Server running at ...`);
});
});
And the login logic
app.post("/dev-end/api/login", async (req, res) => {
await singleAccount(db, req.body.email)
.then(async (response) => {
if (response.code) {
res.render("templateLogin");
}
try {
if (await bcrypt.compare(req.body.password, response.password)) {
const user = { id: response._id, name: response.name };
await deleteTokenById(db, user.id.toString());
const accessToken = generateAccessToken(user);
const refreshToken = jwt.sign(
user,
process.env.REFRESH_TOKEN_SECRET,
{ expiresIn: "604800s" }
);
createToken(db, {
_id: user.id,
accessToken: accessToken,
refreshToken: refreshToken,
createdAt: new Date().toISOString().slice(0, 19).replace("T", " "),
}).then(
res
.cookie("access_token", accessToken, {
httpOnly: true,
maxAge: 60000 * 60 * 24 * 7,
})
.redirect("/dev-end/dashboard")
);
} else {
res.render("templateLogin");
}
} catch {
res.status(500).send();
}
})
.catch(console.log);
});
=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>
const singleAccount = async (conn, email) => {
return await read(conn).then((res) => {
if (!res.code) {
const result = res.find((e) => e.email.toString() === email);
if (!result) {
return {
code: 404,
msg: "No account was found with the provided id",
};
}
return result;
}
return res;
});
};
=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>=>
const read = async (conn) => {
const sql = `SELECT * FROM accounts`;
return await conn.promise().query(sql)
.then(([res, fields]) => res);
};

make button in html delete a row in MySql

i am currently working on a project where i use nodejs to make a user that adds users to MySql in a table called "users"
i would like to make a button in html which deletes the currently logged in user from the mysql table
how do i make a button in html call a function in nodejs which deletes a Row in MySql
This may be a good start to understand how to trigger API calls from Js
fetch('https://reqres.in/api/deleteUser', {
method: "DELETE",
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
id: '1'
})
})
.then(res => {
if (res.ok) { console.log("HTTP request successful") }
else { console.log("HTTP request unsuccessful") }
return res
})
.then(res => res.json())
.then(data => console.log(data))
.catch(error => console.log(error))
And then for NodeJs
// Module dependencies
var express = require('express'),
ejs = require('ejs'),
fs = require('fs'),
mysql = require('mysql');
// Application initialization
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '' //<your password
});
var app = module.exports = express.createServer();
// Database setup
connection.query('CREATE DATABASE IF NOT EXISTS test', function (err) {
if (err) throw err;
connection.query('USE test', function (err) {
if (err) throw err;
connection.query('CREATE TABLE IF NOT EXISTS users('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'name VARCHAR(30)'
+ ')', function (err) {
if (err) throw err;
});
});
});
// Configuration
app.use(express.bodyParser());
// Post delete user
app.post('/deleteUser', function(req, res) {
var id=Number(req.query.id);
console.log(id);
connection.query('delete from users where id='+id,
});

Node.js, Mysql TypeError: Cannot read property 'apikey' of undefined

I am working on a basic auth middleware for a API it uses Node.js Mysql but if someone puts a incorrect key in auth header and sends the request the entire API crashes heres my code the issue is with the callback but I don't know how to fix that.
var express = require('express');
var app = express();
app.get('/', (request, response) => {
response.sendStatus(200);
});
let listener = app.listen(3000, () => {
console.log('Your app is currently listening on port: ' + listener.address().port);
});
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
database : 'systemdata'
});
connection.connect();
function systemAuth(apikey, callback)
{
connection.query('SELECT apikey FROM systemdata.systemkeys WHERE apikey = ?', [apikey], function(err, result)
{
if (err)
callback(err,null);
else
callback(null,result[0].apikey);
});
}
var auth = function (req, res, next) {
systemAuth(req.headers.apikey, function(err,data){
if (err) {
console.log("ERROR : ",err);
} else {
console.log("result from db is : ",data);
}
if(data == req.headers.apikey) {
next()
}else{
res.status(401).send({"error": "Missing or Invalid API-Key", "apikey": req.headers.apikey, "valid": "false"})
}
})
}
app.use(auth)
You will also have to check whether your result actually contains any rows.
A query not returning any rows is not an error, so err won't be set, if result is an empty array. And accessing an element by an index which does not exist leads to undefined, thus the error you are seeing.
function systemAuth(apikey, callback)
{
connection.query('SELECT apikey FROM systemdata.systemkeys WHERE apikey = ?', [apikey], function(err, result)
{
if (err) // some error with the query
callback(err,null);
else if (!result || result.length == 0) // no matching rows found
callback(new Error("invalid apikey"), null);
else // a matching row is found
callback(null,result[0].apikey);
});
}

How do you return a JSON response to a route after a query in MySql?

I'm using elasticsearch, node, and MySql. I need to sync some user data from MySql to elasticsearch. My route is set up like:
router.post("/register_user", (req, res, next) => {
mysql.register(req.body).then((result) => {
elastic.createUser(...);
});
});
When a user posts to this route, it successfully creates a row in mysql:
const mysql = require("mysql");
const connection = mysql.createConnection("...");
connection.connect();
exports.register = (req, res) => {
const user = { name: req.name };
connection.query('INSERT INTO user SET ?', user, (err, rows) => {
// stuff for errors
// ...
connection.end();
// what do I do here?
});
});
I tried:
// I got an error regarding "status of undefined"
res.status(200).json({ id: rows.insertId });
// I got something about "then of undefined" in the router
return { id: rows.insertId };

How do I pass mysql database content to a different page?

I am trying to display my database content to an ejs web page. However, I am running into a problem when trying to pass the content between pages.
I have a JavaScript page "store.js" which has the server running:
store.js-
var express = require('express');
var dbcon = require('./app/db/databaseconnection');
//var path = require('path');
//dbcon.connection;
var app = express();
var router = express.Router();
dbcon.connect();
console.log(dbcon.getproducts());
//var filepath = path.join(__dirname, '../../views/')
var filepath = __dirname + '/views/';
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use('/', router);
router.get('/', (request, response) => response.render(filepath + 'index', { page_name: 'home' }));
router.get('/store', (request, response) => response.render(filepath + 'store', { page_name: 'store' }));
router.get('/about', (request, response) => response.render(filepath + 'about', { page_name: 'about' }));
router.get('/contact', (request, response) => response.render(filepath + 'contact', { page_name: 'contact' }));
router.get('/build', (request, response) => response.render(filepath + 'build/build'));
router.get('/learn', (request, response) => response.render(filepath + 'learn/learn'));
app.use('*', (request, response) => response.render(filepath + '404', { page_name: '404' }));
app.listen(3000, () => console.log("Server running at Port 3000"));
Then I have a JavaScript page which includes the database connection:
databaseconnection.js-
var mysql = require('mysql');
var connection = mysql.createConnection(conObject = {
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
connect: () =>
{
connection.connect((error) => {
if (error) throw error;
console.log(conObject.database + " connected!");
});
},
// The display method prints the returned result to the console.
// Change this to return the result. Maybe a toString() ?
getproducts: () => {
/*var result = */connection.query('SELECT * FROM products', (error, result) => {
return result;
//return result;
// console.log(result);
// How to get certain properties
// console.log(result[0].brand);
// console.log(result[0].series);
// console.log(result[0].model);
});
//return result.result;
},
createdb: () => {
},
createtable: () => {
},
populatetable: () => {
}
}
So on the store.js page I have the console.log(dbcon.getproducts()); Which I was hoping would display the database content of the "products" table. However I keep getting undefined. Basically, I can't get it to pass from the database connection page to the store.js page.
If I get this to work, my next step would be to find a way to display the products table to an ejs page. I've been trying to solve this for a while now so any help would be appreciated! Thank You!
Following up my comments, here's how you can modify databaseconnection.js module to use a connection pool and return query results via Promises:
Note: the code is mostly untested
const mysql = require("mysql");
const pool = mysql.createPool({
connectionLimit: 10, // adjust this according to your needs
host: "localhost",
user: "root",
password: "LOTOS123l",
database: "dbComputerStore"
});
module.exports = {
// you don't need the connect method anymore
getProducts: () => new Promise((resolve, reject) => {
pool.query("SELECT * FROM products", (error, results, fields) => {
if (error) {
reject(error);
} else {
resolve(results);
}
});
}),
// ...
};
then in store.js, you can do:
const dbcon = require('./app/db/databaseconnection');
dbcon.getProducts()
.then(results => {
console.log(results);
})
.catch(err => {
console.error(err);
});
// or you could use async/await syntax:
const asyncFn = async () => {
try {
const results = await dbcon.getProducts();
console.log(results);
} catch (ex) {
console.error(err);
}
};
asyncFn();