Azure Windows Server 2019 NodeJS MySQL Client Timezone Problem - javascript

i have migrated from
Local
Windows 10
NodeJS
MySQL NPM 2.18.1
to
Azure Virtual Server
Windows 2019
NodeJS
MySQL NPM 2.18.1
I wrote an test script:
var util = require("util");
var mysql = require("mysql");
(async ()=>{
const conn = mysql.createConnection({
host: "XXXXXXXXXXXXXXXXXXX",
user: "XXXXXXXXXXXXXXXXX",
password: "XXXXXXXXXXXXXX",
database: "XXXXXXXXX"
});
var query = util.promisify(conn.query).bind(conn);
let data = await query("select * from xxxx where csv_datei_datum = '2023-01-31' and trip = 754");
console.log(data)
})();
I tested it on both machines.
Result Local: 2023-01-31T11:59:56.000Z
Result Azure: 2023-01-31T12:59:56.000Z
The correct one is the result from the local machine.
How is that possible?
Do you have any idea?
Kind Regards
I tested the same script on different machine.
Same Versions.
The Machines are in the same timezone.
I expect to get the same results

Related

Error: listen EADDRINUSE: address already in use :::3306

I'm trying to create a log system with MySQL and Node.JS. But I'm getting the error you see below, I'm still actively looking for a solution, but I couldn't find it. And I decided to ask you.
.env
DB_HOST = 127.0.0.1
DB_USER = newuser
DB_PASSWORD = password123#
DB_DATABASE = userDB
DB_PORT = 3306
PORT = 3000
Node.js
const express = require('express');
const app = express();
const mysql = require('mysql');
require('dotenv').config({path: './dbInfo.env'})
const db = mysql.createPool({
connectionLimit: 100,
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
port: process.env.DB_PORT
})
db.getConnection( (err, connection) => {
if (err) throw (err)
console.log("DB connected succesful:" + connection.threadId)
})
const port = process.env.DB_PORT
app.listen(port,
() => console.log('Server started on port ${port}...'))
console.log(process.env.DB_PASSWORD)
It seems the Port 3306 is already used. 3306 is the MySQL standard port, so most likely your MySQL instance is already running which you would want.
You can only have one service running behind a port. That's the purpose of ports to direct traffic to the process that can deal with that traffic or expects that traffic.
To resolve the issue use const port = process.env.PORT instead of const port = process.env.DB_PORT. Your Express server then runs on port 3000 and your MySQL server on port 3306.
FYI: You should specify some default values (or errors) in case the environment variables are not set. You might have set them here with your .env file both you might wanna run the server in another environment some day and you'll forget to configure something and wonder why your server is crashing.
One quick and easy solution that will do for starters could be to use logical OR (||). This will set the port set in the environment variables or the default value of 3000.
// Mocking process.env
const process = { env: {}}
// process.env.PORT is not defined here so the default value will be used
const port = process.env.PORT || 3000;
console.log(`Port: ${port}`)
You might also be interested in the dotenv npm package.

why .Net.createConnection doesn't work on a browser and how to solve this?

I'm trying to setup a database connection with my web-application (I'm using XAMPP - phpmyadmin).
In this milestone, I came across Node.js for the first time and managed to make the require() function to work by using browserify. This is my javascript file that is executed when clicking the Sign-Up button on the register.php.
var mysql = require('mysql');
var thisUser = mysql.createConnection({
host: "localhost",
user: "admin1",
password: "password",
database: "db_mymindmapper"
});
------------- WORKS UNTIL HERE -------------
thisUser.connect(function(error){
if(!error) {
alert("NODE CONNECTED TO MYSQL SERVER");
var sql = "INSERT INTO student_demographics (first_name) VALUES ('YOU DID IT MF')";
thisUser.query(sql, function(err, result) {
if(!err){
alert("result = " + result);
}else{
throw err;
}
});
}else{
throw error;
}
});
When I run this on a browser using my register.php file it gives the following error on the console:
Uncaught TypeError: Net.createConnection is not a function
at Connection.connect (bundle.js:34538)
at HTMLInputElement.check_Register (bundle.js:43660)
connect # bundle.js:34538
check_Register # bundle.js:43660
However when I run this in CMD using node signUp.js is works perfectly and data goes to the table on the phpmyadmin.
I know this is caused by this reason in the provided question: "You must run this particular module on Node.js only, you can't run it in a web browser."
MY QUESTION:
Is there any possible way to run this on browser so that users when accessing the register.php site could register? Do I need to change the entire structure of my code? Do I need require('http') to set a Node.js server?
So to answer my own question, I solved this by indeed creating a node.js server. To do this I used the terminal within Visual Studio Code (CMD will also work).
cd directoryOfTheApplication //(change the directory of the terminal)
npm init //(creates a package.json file within directory of the application)
npm install express //(modifies the package.json and add modules within node-modules folder)
create a new .js file in the directory (I called mine server.js).
//USE `nodemon scripts/server.js` on Terminal to autosave the server files.
//My modules
const express = require("express");
const morgan = require("morgan"); //GET INFORMATION ABOUT THE SERVER REQUESTS (OS, Browser,time, ...)
const mysql = require("mysql");
const app = express();
app.use(morgan('combined')); //'short', 'combined'
app.get("/users/:id", (req, res) => {
const userID = req.params.id;
console.log("Fetching user with id : " + userID);
//get data from DB
const connection = mysql.createConnection({
host: "localhost",
user: "admin1",
password: "secret",
database: "myDB"
});
let sql = "SELECT * FROM student_demographics WHERE id =?";
connection.query(sql, [userID], (err, rows, fields) => {
console.log("Fetching users was successful");
res.json(rows);
});
//res.end();
});
app.get("/", (req, res)=>{
console.log("responding to root route");
res.send("hello world from root");
});
app.get("/users", (req, res)=>{
const user1 = {
firstName: "name1",
lastName: "name2"
};
const user2 = {
firstName: "name3",
lastName: "name4"
};
res.json([user1, user2]);
});
app.listen(81, ()=>{
console.log("Server running on port 81");
});
Once again in terminal, you may wish to install nodemon so that you don't have to start the server manually. This will refresh and update the server when saving the file (in this case server.js). Also morgan will basically collect information regarding the request of the user. In terminal it would look like this:
PS C:\inetpub\wwwroot\mymindmapper> nodemon scripts/server.js
[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 scripts/server.js`
Server running on port 81
Fetching user with id : 1
Fetching users was successful
::1 - - [14/Jun/2020:11:15:20 +0000] "GET /users/1 HTTP/1.1" 304 - "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.97
Safari/537.36"
The other module mysql is for the sake of this example, but I guess it would work with any modules. I basically followed the tutorials of this brilliant person on YT.
Setup express: NodeJS REST API: Super Simple Setup - Express & NPM (Ep1)
Setup DB: NodeJS REST API: Connecting to MySQL (Ep 2)

unable to connect to database from node script and there is no error thrown

I have been working with nodejs google cloud functions for a while. I have been facing a weird issue where I can't connect to database servers and there is no error logged not even timeout. I am using node v14.2.0 with pg as postgres library. My nodejs code is
const { Client } = require('pg');
let connectionSetting = {
host: "host",
user: "user",
database: "db_name",
password: "password",
};
const client = new Client(connectionSetting);
console.log(connectionSetting);
client.connect(err => {
if (err) {
console.error(`Error connecting to db -> ${err}`);
}
console.log("Connection established with PgSql DB ");
});
There are no console logs or whatever.
This same code is working on other systems. The database is remote database hosted on gcp and I'm able to connect to it using tablePlus as GUI client.
Any help appreciated.
I found the issue. It has to do with the node version. I was using node current 14.2.0 so I installed node lts 12 and then everything works fine.
Thanks for all help

Error: read ECONNRESET when connected to a mysql server with Node.js

I'm trying to establish a simple connection to my database with the mysql npm package. At first glance, everything works fine and I can get the information I need, however, if I leave the server running for some time I get the following error:
Error: read ECONNRESET
at TCP.onStreamRead
const express = require('express');
const app = express();`
const mysql = require('mysql');
const db = mysql.createConnection({
host: 'XXXX.mysql.database.azure.com',
user: 'XXXXX',
password: 'XXXXX',
database: 'XXXXX'
})
db.connect((err)=>{
if(err){
console.log(err.message);
} else {
console.log('Connected to the database');
}
})
As far as I understand the problem stems from the database connection being in idle mode. Do I need to configure the Azure server or is there something else I need to do?
Couple of things to try:
You can try creating connection pool instead of **createConnection**
mysql.createPool({});
Modify your package.json like below:
"dependencies": {
"mysql": "git://github.com/mysqljs/mysql#e3e123e9af7c0829a6c1417d911572a75b4a5f95"
},
It is described in detail here:
Bad handshake or ECONNRESET Azure Mysql Nodejs
https://social.msdn.microsoft.com/Forums/en-US/c8fedbcc-909d-41ce-8c72-0374f76fdf82/cannot-connect-from-nodejs?forum=AzureDatabaseforMySQL
Hope it helps.

NodeJS disconnecting when attempt MongoDB connection

In my app.js file, I have the following code
var express = require('express');
var app = express();
var port = 8080;
var util = require('util');
var router = require('./base/js/routes.js');
//==================================================================
app.use('/', router);
// start the server
app.listen(port, function(request, response) {
console.log('Port 8080: Server Begins');
});
//==================================================================
var ipaddress = '123.456.789';
//==================================================================
var mongoose = require('mongoose');
var mongoURI = "mongodb://"+ ipaddress +":27017/test";
var MongoDB = mongoose.connect(mongoURI);
MongoDB.on('error', function(err) {
console.log(err.message);
});
MongoDB.once('open', function() {
console.log("mongodb connection open");
});
//==================================================================
The line var MongoDB = mongoose.connect(mongoURI);
is causing nodeJS not to work. I do not know why. NodeJS is on port 8080 and MongoDB is on port 27017.
I am fairly certain I installed mongodb package (and opened the port correctly). I just do not understand why nodeJS doesnt work when i include that connection line.
Side Note: Also I have the package forever installed: forever start -c nodemon app.js for nodeJS. If that is any relevance.
You are using wrong IP address format.
First try to connect with your local mongoDB instance if it work then you to check the IP address your trying to connect is correct or not.
Add the correct error message if problem still remain same.
change your mongod.conf file from /etc folder
In mongod.conf you need to change bindIp
If connection is local then set bindIp as
bindIp = 127.0.0.1
and if you want to use remote database then change bindIp as
bindIp = 0.0.0.0
then restart mongo service
hope this helps...

Categories