I was developing a CRUD web app through the use of express js, node js and a local SQL database (MySQL) locally, but now it's time to move to the web and I chose an apache web server that supports MySQL.
I already have the database loaded on the Apache web server.
I have already modified the credentials for the connection to the web server (I know that they are correct because I am connected via MySQL local server to it via a tunnel), through something like that:
app.use(
connection(mysql,{
host: '127.127.127.127', //'web hostname'
user: 'root',
port: '80',
password : 'password',
database:'db_name'
},'pool') //or single
);
But when I'm going to query on it I get an error on the connection.query() command:
... throw err; // Rethrow non-MySQL errors
^
TypeError: Cannot read property 'query' of undefined ...
for example in this part of the code:
exports.view1 = function(req, res){
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM table',function(err,rows)
{
if(err){
console.log("Error Selecting : %s ",err );
}else{
res.render('view',{page_title:"Table view",data:rows});
}
});
});
};
1) I'm sure that this error is due to the fact that the connection variable is empty, so it is not possible to perform the query, every help is welcome.
2) I have not found much on the net, but is it possible to continue to use express js even on an Apache web server? Do I have to change something in the formulation of database queries?
[SOLVED] Maybe it can help someone in my same situation. I had to change servers online, going from a Mysql server to a node js, in order to already have the basic functionality of node for the management of my app. However I had to install the mysql-server package, but the connection to my app express js, once moved from local to the server, with the right credential changes, worked properly.
Related
So I have a simple NodeJS bot that makes use of MySQL to store data.
I initialize mysql by using the createPool function.
I find that this works fine, even if my server is dead. I can run it and no errors are fired, but when I run any code that uses a query on the server, then it will fire errors if the server is off.
I want to simplify this by simply forcing a message / error if the bot is started and the server is not online.
This is the code that I have setup so far. Ignore the dotenv stuff, its just to keep my login / database info out of the code.
const mysql = require("mysql");
const path = require('path');
const envconfpath = path.join(__dirname, './.env');
require('dotenv').config({ path: envconfpath });
const connectionPool = mysql.createPool({
connectionLimit : 999,
host: process.env.HOSTNAME, database: process.env.DATABASE,
user: process.env.USERNAME, password: process.env.PASSWORD
});
// This is the code that does not function.
connectionPool.getConnection((err, con) => {
if (err)
console.warn(`Databased failed to start with error: ${err}`);
if(con.state === 'disconnected')
console.log(`Database connection failed. Check that its running and that your configuration is correct`);
else
console.log('Database connection successful');
});
Now, I do want to clear up any possible misunderstanding, I can use my database fine, I simply want to fire an error on initial run if the database's server is not online.
The bottom of that code that gets the connection and runs checks seems to always fire an error. Ive tried various methods for checking whether the server was online, but the code above was made by using examples from the mysql / nodejs documentation
This is the error that it fires, which makes no sense. If the pool is valid (which it is) the getConnection function (which is used on the module's documentation) should return a connection just fine. It says that the state of the connection is invalid, yet I can query the connection fine in other parts of the code outside of the small part I pasted in here.
As for the ACCESS DENIED part? No clue. I run the database both remotely and locally, Ive verified that both worked, and during testing, I dont use a password. This is a completely open database running locally on my system, so I dont see why it would have access issues.
Databased failed to start with error: Error: ER_ACCESS_DENIED_ERROR: Access denied for user 'USER'#'HOST' (using password: NO)
----- UNCAUGHT EXCEPTION -----
TypeError: Cannot read properties of undefined (reading 'state')
I am working on an Azure app services in conjunction with a flexible mysql database server. I have successfully deployed my website to NodeJS v18.LTS, but my server is Throwing: SequelizeHostNotFoundError: getaddrinfo ENOTFOUND mynameserver.mysql.database.azure.com in my app services log stream. In the following question I find a possible solution by adding the ip address of the connecting host to my database instance instead of a FQDN https://stackoverflow.com/questions/25521755/errorerror-getaddrinfo-enotfound-mysql.
However, this configuration is completely discouraged.
https://techcommunity.microsoft.com/t5/azure-database-for-postgresql/dns-configuration-patterns-for-azure-database-for-postgresql/ba-p/2560287
How can I correctly set up my Flexible Server for MySQL instance to work in my production App Services environment without violating this policy?
this is my connection instance configuration:
const sequelize = new Sequelize(
process.env.DATABASE,
process.env.USER,
process.env.MySQLPASSWORD,
{
host: process.env.HOST, // String conection xxxx.mysql.database.azure.com
dialect: process.env.dialect,
});
here I have an alternate approach of connecting to azure MySQL flexible server where I have used mysql2 npm package.
now here I am directly hard coding config data in the code, but you can easily read the application setting using same way you have used before just make sure that you first reading the respective setting for e.g.: username in a variable and then add that variable while configuring the connection to MySQL .
var username = process.env.USER
Here we use the create connection function to connect to the MySQL database and then use the query function to runa query .
The below is code form an express api:
app.use('/', (req,res)=>{
const mysql = require('mysql2');
const connection = mysql.createConnection({
host:'',
user:'',
database:'',
password:'',
port:'',
});
connection.query("CREATE TABLE TESTTABLE ( TEST int)",(err)=>{
console.log(err);
});
res.send("Hello World");
});
Here I have connected the database to MySQL Workbench where I created the table using the above code.
Here in the server I have disabled the ssl mandate
const mysql = require('mysql');
const dbConn = mysql.createConnection({
host: 'xx.xxx.xxx.xx',
database: 'ucha_txxxxxx',
user: 'ucha_axxxxxx',
password: 'txxxxxxxxxxxx',
port: 8090,
});
dbConn.connect(function (err) {
if (err) {
console.log("Error in connection request", err);
return;
}
console.log("Connection Successful-----------------------");
});
module.exports = dbConn;
This is my code for Database Connection. Initially I used phpMyAdmin localhost for testing my app, since I have to deploy my application, I have to change my database from localhost to a private server. I added the details of the private server and that is where I am facing the problems. I checked multiple times if I had entered the right details. I even tried using Pool but had the same issue. To check if my database connection has been established, I run
node index.js
in my terminal. It should display either of the two results written in dbConn.connect(), but I am getting neither. I even tried adding connection Timeout too but couldn't get any results. Please let me know if I am doing anything wrong.
FYI- I am using Webserver enter image description herefor hosting my database
Here is a screenshot of my code snippet.
I tried solutions from multiple websites and YouTube videos, even consulted my senior developer but couldn't get the expected result. I am hoping to get any kind of help from here.
Port 8090 is running a HTTPs Server on your IP, MySQL/MariaDB runs on Port 3306 (which is also open to anyone - more on that later)
The error you described shows that your user is not allowed with that specific IP (probably your IP address of your (home?-)router).
Usually you create user and permissions like this:
CREATE USER '<username>'#'<ip or host>' IDENTIFIED BY '<password>>';
GRANT ALL PRIVILEGES ON <database>.<table> TO '<username>'#'<ip or host>';
If you want to access it from any host you can use % as < ip or host >
WARNING: You should never ever access MySQL over the internet (which looks to me like you do). Usually you don't even want to expose MariaDB to the internet (bind-address in MySQL/MariaDB configuration)
You also have many other ports open to anyone in the world - please check if all of them need to be exposed. Also you maybe want to mask the IP you used in your question.
If you are developing locally its probably best to install a MariaDB locally on your PC (e.g. via Docker) - if you have to use that specific server you should do it over some sort of Tunnel (VPN, SSH).
I'm trying to deploy my NodeJS app on Google Cloud services and getting the following error hen I try to call a database query using Postman through localhost/8080, which is where my server is listening: connect ENOENT /cloudsql/<MY_CONNECTION_NAME>. Here's my database connection file, config.js:
const mysql = require('mysql');
const dotenv = require('dotenv');
dotenv.config();
const {
DB_PASS,
DB_USER,
DB_NAME,
} = process.env;
const config = {
user: DB_USER,
password: DB_PASS,
database: DB_NAME,
socketPath: `/cloudsql/${process.env.CLOUD_SQL_CONNECTION_NAME}`,
};
const connection = mysql.createConnection(config);
// create connection
connection.connect((err) => {
if (err) throw err;
console.log(`Connected to database ${DB_NAME}`);
});
module.exports.connection = connection;
I know that Google recommends using a pool to connect, but I'm afraid that doing that will require me rewriting all my database queries, and I'm on a tight deadline.
I've been able to successfully shell into the database with MYSQL using the terminal.
Take a look at the Connecting to App Engine page. In particular, here are some things you should check if the socket isn't present:
For GAE Flex, make sure you have the following in your app.yaml:
beta_settings:
cloud_sql_instances: <INSTANCE_CONNECTION_NAME>
Ensure the SQL Admin API is enabled and make sure you have the correct IAM permissions (Cloud SQL Client1 or higher) on your service account (service-PROJECT_NUMBER#gae-api-prod.google.com.iam.gserviceaccount.com`). If between projects, make sure you have the
Make sure you are spelling <INSTANCE_CONNECTION_NAME> correctly. It should be in the format <PROJECT>:<REGION>:<INSTANCE> - you can copy it exactly from the "Instance Details" page for your instance.
Additionally, using a connection pool will have no effect on your queries. Using a pool only means that when you "open" a connection, it is actually reusing an existing connection, and when you "close" a connection it puts it back in the pool for your application to use elsewhere. The queries you perform using the pool should be exactly the same.
this is happen if you are using flex as env in app.yaml to run without errors remove the env:flex from your app.yaml,
your app.yaml need to look like this
app.yaml
and you will successfully connected to the cloud sql without causing errors
console log
I am currently in the process of creating an app and I am using node.js, express, and MySQL. I feel that I am in a bit of a rut in connecting my server to my database. Here's how I see things so far
server.js
var express = require('express');
var app = express();
//These are just my static finals so this can be ignored for now
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/public/views'));
app.use(express.static(__dirname + '/public/controlers'));
app.listen(3000);
console.log("Listening at 3000")
Here I am setting up a local server on my computer that is listening on port 3000. What I am hoping to do here eventually is handle post requests. My goal is to ensure that post requests are inserted into the database. So I realize that I need to do two things create a database and a schema for my database. For now I just want to create a simple table with an ID and first_name columns. I am using this driver https://github.com/felixge/node-mysql/.
So my next step is creating a connection
dbconnection.js
var mysql = require('mysql')
var app = require('../server.js');
var connection = mysql.createConnection({
host : 'localhost',
port : 3000,
user : 'username',
password : 'password',
database : 'liveDatabase'
});
connection.connect()
//queries and error handling go here
connection.end()
This is where I lose touch with my program.
Here's what I don't understand:
I don't get how a connection is being created to my localhost:3000. I see the key values for host and post being assigned to localhost and 3000 and I am requiring my server in the db.js file (var app = require('../server.js');. Is this all that is needed to create a connection? How does it find localhost:3000? I am guessing this is all happening under the hood, but I feel a little stuck here.
I have confusion about the database as well. Where should my database be created and live in order for .createConnection to be able to find it. Do I create a separate .sql file then just create my database and table(s) there and require(/database/path) in my dbconnection.js?
Any help is appreciated. Thanks!
This is just a start, but this seems to be the crux of the misunderstanding:
Your server.js is creating a web server that listens on port 3000. Your dbconnection.js is trying to connect on that server on port 3000. That's not right. You want it to connect to your MySQL server instead.
It seems more logical for server.js to require dbconnection.js rather than the other way around. Then server.js can send/receive info with the database via the required module.