Goal: Do a simple query to the database.
Expected results: "please print something!" and the results from the query are printed on the terminal.
Actual results: Nothing is printed on the terminal.
Errors: No error message.
Here is the db.js file:
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'todoDB'
});
connection.connect();
connection.query('SELECT * FROM categories', function (err, res, fields) {
console.log("please print something!")
if (err) throw err;
console.log(res);
});
connection.end();
I execute this file using:
node db.js
On the mysql cli, I am able to do this query without any problem with the database name, credentials, and query given above.
I know that connection.connect() works since when I'm inputting the code below, the terminal prints "Database is connected!" I think the problem occurs at connection.query, but I am not sure why.
connection.connect(function(err){
if(!err){
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
console.log(err);
}
});
I've looked through all the related questions on stackoverflow and tried them, but none of the solutions seems to resolve the problem that I have.
So it looks like mySQL V8 uses caching_sha2_password as the new authentication standard, which the nodeJS plugin does not support. Connect to your db and try creating a new user that uses the native password auth type.
CREATE USER 'foo'#'localhost' IDENTIFIED WITH mysql_native_password BY 'bar';
Related
I am trying to create an API where I can query information from a database. The DB is hosted on my university's computer cluster. Here is the code I currently have
const Pool = require('pg').Pool
const pool = new Pool({
user: 'username',
host: 'hostname-of-school-computer',
database: 'db-name',
password: 'pass',
port: 5432
})
const getUsers = (request, response) => {
pool.query('SELECT * FROM Inventory ORDER BY ingredient_id ASC', (error, results) => {
if (error) {
throw error.message
}
response.status(200).json(results.rows)
})
}
When I run this code and make a request on localhost, I get the error
no pg_hba.conf entry for host "165.xx.xx.172", user "username", database "db-name", SSL off
I tried adding ssl: true to the pool config but then got the error self signed certificate in certificate chain. Additionally, I have tried editing pg_hba.conf to listen to my school's host IP and that neither worked.
These are the lines I added to pg_hba.conf:
# TYPE DATABASE USER ADDRESS METHOD
host all all 0.0.0.0/0 md5
host all all 165.xx.xx.172/0 md5
I am kind of a noob when it comes to JS and postgres so please any help would be greatly appreciated.
I'm quite new with the implementation of Oracle database with Node.js, currently I'm using oracledb library to connect my Node.js app to my Oracle database as follows
connection = await oracledb.getConnection({
user: "SYS",
password: password,
connectString: "localhost:1522/userdb",
privilege: oracledb.SYSDBA
});
I set everything up as a monolithic app(It's a simple user review app) to start, but I want to split the code in User and Review Controller, the same for the service, model for both objects.
The only problem I have now (That I know of), is that I am not able to make each model (User and Review) to take that connection and simply send a query depending on what the controller needs. I tried to create a separate db.js file and set the connection there and then use
class DBConnection {
constructor() {
this._connect();
}
async _connect() {
try {
connection = await oracledb.getConnection({
user: "SYS",
password: password,
connectString:process.env.DATABASE,
privilege: oracledb.SYSDBA
});
} catch (err) {
console.log(err.message);
}
}
}
module.exports = new DBConnection();
Then I would try to import it and use something like:
connection= DBConnection();
connection.execute(query);
But it has not worked, is there any way to do this?
I'm currently working on a app (dev with electron). I'm using mongoDB and mongoose for my persistant storage but I can't find a way to do something that seem really basic : when creating a database I'd like to add an user and a password to it (I realy search for it, but no way to find anything usable).
I have this need because it's going to be a multi-user app and I definitly don't want an user to know the contents of another user account.
The idea is that once you create an account, the app create a database that has the same username and password of the account. For login, the app try to connect you to the database with your account & password.
I'm working with :
electron
HTML / CSS / javascript
mongoDB
mongoose
Here is the code that I tested :
var mongoose = require('mongoose');
var connStr = "mongodb://localhost:27017/test";
mongoose.connect(connStr, {user: 'newUser', password: 'pwd', useNewUrlParser: true }, function(err) {
if (err) {throw err};
console.log("Successfully connected to MongoDB");
});
I get the error
Uncaught (in promise) MongoNetworkError: failed to connect to server [localhost:27017] on first connect [MongoError: password must be a string]
However with those, the database is correctly created (but anyone can access it) :
user: '', password: ''
What I expect is to create a new database with the user name set as "newUser" and the password as "pwd", in that way only with the correct id & password would it be possible to connect to it.
Thanks for your help !
I don't know if this will work or not but I ran a mongo service using docker and then connected mongoose to it with the following code
mongoose.connect('mongodb://user:pass#localhost:port/MyDB?authSource=admin', {
useNewUrlParser: true
})
.then(() => console.log('MongoDB connection successful'))
.catch(err => console.error('Could not connect to MongoDB:', err));
this is equivalent to
mongo --username user --password pass --authenticationDatabase admin --port 27017
I have a server on sails nodejs and I am trying to connect my controllers with my MySQL db through a wrapper file that would create the connection pool. My purpose is that I use that pool everytime a function in any controller needs to interact with DB, and in such a way that connection is created at the time interaction starts and connection is closed at the time interaction is over. For this, I have created a wrapper file db.js
db.js
var mysql = require('mysql');
var connection = mysql.createConnection({
host:"localhost",
port: '3306',
user:"ye_old_username",
password:"ye_old_password",
database: "ye_old_schema"
});
module.exports = connection;
Now, I am creating a connection pool called ConnectionPool.js
ConnectionPool.js
var mysql = require('mysql'),
config = require("./db");
/*
* #sqlConnection
* Creates the connection, makes the query and close it to avoid concurrency conflicts.
*/
var sqlConnection = function sqlConnection(sql, values, next) {
// It means that the values hasnt been passed
if (arguments.length === 2) {
next = values;
values = null;
}
var connection = mysql.createConnection(config);
connection.connect(function(err) {
if (err !== null) {
console.log("[MYSQL] Error connecting to mysql:" + err+'\n');
}
});
connection.query(sql, values, function(err) {
connection.end();
if (err) {
throw err;
}
next.apply(this, arguments);
});
}
module.exports = sqlConnection;
I have followed the method answered on this question to create the connection pool: How to provide a mysql database connection in single file in nodejs
And finally, I am trying to run a function from a controller using the wrapper and the connection pool. The code inside the Controller is
var connPool = require('./ConnectionPool');
module.exports = {
testConn: function(req, res){
connPool('SELECT * from user where ?', {id: '1'}, function(err, rows) {
if(err){
sails.log.debug(err);
}else{
console.log(rows);
}
});
}
};
All the three files, the wrapper, the connection pool, and the controller are in the same Controllers folder.
Now, when I send a request to the URL through my client, that would invoke the testConn function inside the controller, I get the following response on server log:
[MYSQL] Error connecting to mysql:Error: ER_ACCESS_DENIED_ERROR: Access denied for user ''#'localhost' (using password: NO)
This error is coming from the line connection.connect(function(err) { in connection pool file.
When I try to log on my MySQL db through the same credentials on command line, I am through it. Therefore I believe that db.js file has some format related issue because of which a proper connection is not getting initiated. There can be other reason as well, but the reason I suspect seems to be very strong.
I need some guidance on solving this issue. Any help will be appreciated.
I'm having trouble getting the pg package working on my local system. I've tried to run the following:
var pg = require('pg');
var con_string = "postgres://user:password#localhost:5432/documentation";
var client = new pg.Client();
client.connect(con_string, function(err, res) {
// stuff here
});
But I keep getting TypeError: callback is not a function.
Is there a setting that I need to change in order to connect to the db via a connection string? I have tried the username and password that I'm using in user:password above on a database on my local machine and I can connect just fine.
I've also tried in the node shell in the directory of the project where I installed pg and haven't had any luck.
Thanks
This the error that I get from running the answer below:
$ node pg_test.js
error fetching client from pool { [error: password authentication failed for user "jake"]
Directly from documentation at https://github.com/brianc/node-postgres:
var pg = require('pg');
var conString = "postgres://user:password#localhost:5432/documentation";
//this initializes a connection pool
//it will keep idle connections open for a (configurable) 30 seconds
//and set a limit of 10 (also configurable)
pg.connect(conString, function(err, client, done) {
if(err) {
return console.error('error fetching client from pool', err);
}
client.query('SELECT $1::int AS number', ['1'], function(err, result) {
//call `done()` to release the client back to the pool
done();
if(err) {
return console.error('error running query', err);
}
console.log(result.rows[0].number);
//output: 1
});
});