nodejs mysql not using full config - node.js

First of all, I can't find any answers here and Google. I may search the wrong direction and appreciate any help.
Node: 10.24.1/12.22.1/14.17.0/16.3.0 (These are the versions I tried)
Mysql for node: 2.18.1
Knex: 0.95.0/0.95.4/0.95.5 (Versions I tried)
Test environments: two computers (mac & win) in two networks (totally separated)
Background
The code needs to access the mysql database locally. This database has been tested through HeidiSQL(win) and Sequel Ace(mac) on those two computers with the same credentials remotely and successfully.
To avoid interference by other codes, I initiated a new project using npm init. It has one file: app.js and the code is below:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : '123.123.123.123', // Remote database IP
user : 'user_name',
password : 'pass',
database : 'mydb'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) throw error;
console.log('The solution is: ', results[0].solution);
});
connection.end();
200.200.200.200 here is an example of the network's real IP
And the error is below:
code: 'ER_ACCESS_DENIED_ERROR',
sqlMessage: "Access denied for user 'user_name'#'200.200.200.200' (using password: YES)",
sqlState: '28000',
fatal: true
I then clone this mini test project to another computer and tested in a different network with example IP 202.202.202.202 and the error is below:
code: 'ER_ACCESS_DENIED_ERROR',
sqlMessage: "Access denied for user 'user_name'#'202.202.202.202' (using password: YES)",
sqlState: '28000',
fatal: true
Apparently the username has been adapted by the mysql library but the host is not. I assume that the password is taken in as well. because of the using password: YES.
I don't think this is related to the database because without using the correct IP, the code hasn't even touched the database server yet.
It looks like it's using localhost but shouldn't it be 192.168.x.x and I don't use localhost anywhere.
I tried a few versions of node and looks like it's not related to node. knex and mysql are freshly installed using npm. Project is as clean as possible. I can't anywhere that has any problems could cause this.
Any help is appreciated.

Check your database username and password. If it's working before then it should work now and I don't think it's related to node of any of your dependancies.
If it's never working, then try to change your password and try again. From your example the config is used by the mysql lib so there's no reason it picks your username and password but explicitly ignores your host.

Related

connecting mongoose to mongoDB atlas and nodejs

This is my mongoose connection code:
mongoose.connect("mongodb+srv://Sarthak:*******:Wb#cluster0-jli2a.mongodb.net/test?retryWrites=true",{ useNewUrlParser: true })
.then(()=>{
console.log("Connected to mongo database");
})
.catch((err)=>{
console.log("Error connecting mongo database",err);
});
I got the errors below, any idea how to fix this?
Error connecting mongo database { MongoParseError: Unescaped colon in authority section
at parseConnectionString (/home/sarthak/Projects/thePracticalGuide/node_modules/mongodb-core/lib/uri_parser.js:250:23)
at QueryReqWrap.dns.resolveTxt [as callback] (/home/sarthak/Projects/thePracticalGuide/node_modules/mongodb-core/lib/uri_parser.js:126:7)
at QueryReqWrap.onresolve [as oncomplete] (dns.js:240:10)
name: 'MongoParseError',
[Symbol(mongoErrorContextSymbol)]: {} }
Just go to atlas website security tab and edit the password of the user and make sure you do not use "#" or ":". That's it.
You need to encode your password in the connection string:
const connectionString = `mongodb://yourUsername:${encodeURIComponent('yourPassword')}#127.0.0.1:27017/mydb`;
Try to use this way of connection too
/* I've removed the ":Wb" between your password and #clus... As mongoDB atlas website didn't use that in my generated connection string */
mongoose.connect("mongodb+srv://Sarthak:*******#cluster0-jli2a.mongodb.net/test?retryWrites=true",{ useNewUrlParser: true });
mongoose.connection.on('error', (err) => {
console.error(`Mongoose connection error: ${err}`);
process.exit(1);
});
Otherwise things to consider:
Make sure that you've added your connecting device IP address in the IP whitelist in the security tap of your cluster in mongoDB atlas website (if you've already done that you might try giving permission to every IPs by adding 0.0.0.0/0 to check there's no issue regarding to this)
Regarding to the password, you may got confused with the mongoDB atlas login password, than the user you made for the cluster (this is a common mistake that mongoDB atlas newbies make).
If not and you're using the right password, you can try to delete the user and re-create it again in the security tab (in the clusters view in mongoDB atlas website). First consider giving the user a very basic password without any special character and try connecting again to ensure that it's not an encoding issue.
At the end if none of above worked with you try making connection via shell. (you can see the connection string in the mongoDB atlas website, in the connect section of your cluster. There you can get better logs regarding to the cause of your problem.
The error description is pretty clear - do you have a colon in your password? The typical connectionstring format is "mongodb+srv:[username:password#]host1..." so an unescaped colon would throw a parse error.
I had this same problem, also with "unescaped colons" even though they were very clearly escaped. Try this:
var uri = encodeURI('mongodb+srv://Sarthak:*******:Wb#cluster0-jli2a.mongodb.net/test?retryWrites=true');
I was getting "Unescaped colon in authority section" using MongoDB Compass when entering the connection string.
For which -
I went into "Create Free Cluster" button and made a cluster.
Then I got the connection string. However, while entering the available connection string I got the error.
I just changed the password by logging into mongodb atlas.
Here is the procedure I used -->
[1] To change the password - click on encode URI
[2] It will take you here -->
[3] Click on the edit button from the screen above and change your password.
I followed the above steps and was able to login.

Cannot read/write on a MongoDB Atlas database using Mongoose

I have a new sandbox cluster on MongoDB Atlas that I am connecting to with mongoose on a Node.js server. This is the code I'm using to connect:
const mongoDbUrl =
`mongodb+srv://${username}:${password}#mydb-sandbox-12345.mongodb.net/testdb`
mongoose.connect(mongoDbUrl)
const connection = mongoose.connection
connection.on('connected', () => {
console.log('Connected to mongodb')
})
In the Atlas dashboard I have a readWriteAnyDatabase user that I am authenticating with. Authentication works as expected. I am able to connect to the database and no error is thrown on the connection. I can confirm this by removing a character in the password - authentication fails and I'm unable to connect.
The problem is when I try to insert documents.
const UserModel = require('./models/User')
UserModel.create({
name: 'Hello Atlas'
})
I get the following error:
MongoError: not authorized on admin to execute command {
insert: "users",
documents: [
[{
name Hello Atlas
} {
_id ObjectIdHex("5aa17933d72d25730a340611")
} {
__v 0
}]
],
ordered: false
}
As far as I know the user I'm authenticating with should have permission to read and write on the database I'm connecting to. The other part I don't understand is that the error shows that it's trying to write to admin even though my url is connecting to testdb.
Not sure if you have seen this post, but it could be because you are on a free cluster? Hope this helps.
UPDATE
I looked into the problem further and reproduced it on my own. I got the same error. However, I noticed that at one point Atlas provided me with a choice of connection strings. I went back to that page and chose I am using driver 3.4 or earlier.
The connection string looks like this:
const mongoDbUrl = `mongodb://${username}:${password}#cluster0-shard-00-00-1wntz.mongodb.net:27017,cluster0-shard-00-01-1wntz.mongodb.net:27017,cluster0-shard-00-02-1wntz.mongodb.net:27017/testdb?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin`;
It worked with that connection string.
It looks like the free version of MongoDB Atlas launches with v3.4
If you are using free cluster. change 'admin' to 'test' in the path:
mongodb+srv://username:password#cluster0-yauj8.mongodb.net/test?retryWrites=true&w=majority
This worked for me
Going off #rithesh-mys 's answer. Replacing it with "test" is specifying the db. So you have to change it to the db name that you would use.
I had the same problem. I was trying a lot of connection strings, but the one for olders mongo shell (3.4 or earlier) worked for me.
mongodb://my_username:my_password#cluster0-shard-00-00.osobw.mongodb.net:27017,cluster0-shard-00-01.osobw.mongodb.net:27017,cluster0-shard-00-02.osobw.mongodb.net:27017/my_database?ssl=true&replicaSet=atlas-xw3rfy-shard-0&authSource=admin
I think that newer versions of connection strings don't work with mongoose, at least with free clusters.
Make sure the user you have created has the write and read privileges.

How to connect to a postgreSQL database stored on a server and request this database? Node.js

I am working to develop a server with Node.js to request a postgreSQL database. My problem is, that I can't connect (with my local computer, using wifi connection, not ethernet) to this server, and also to the postgreSQL.
I have an username and a password to connect to the server, and also an another username and password to connect the database.
How can to connect both of those, and get the information I want from the postgreSQL database? Can I connect to this server with command bash like ssh but in node.js?
I did something like this:
var ssh = new SSH({
host: 'hostname',
user: 'user',
pass: 'password'
});
or something like this:
var connectionString = 'postgres://user:password#database:port';
I have another problem, my teacher give me a password containing a #, and I think this will make some problems when I have to put my password:
postgres://user:pass**#**word#database:port
How to bypass this password problem?
you need to pass ip address of machine where database resides in place of hostname.

Auth failed, code 18 when connecting to MongoLab database

I'm trying to connect to a MongoLab database but keep getting the following error on connection:
{ [MongoError: auth failed] name: 'MongoError', ok: 0, errmsg: 'auth failed', code: 18 }
The code I'm using to connect is:
var mongoose = require("mongoose");
mongoose.connect("mongodb://username:password#ds061474.mongolab.com:61474/apitest");
mongoose.connection.on('error', function (err) {
console.log(err);
});
When I connect using the shell, I have no problems whatsoever. What am I doing wrong?
I have encountered similar problem when connecting the mongo db using mongoose. After exploring a while I found mongoLab is using SCRAM-SHA-1 authentication.
Refer to the question below I tried to upgrade my mongoose to V4.1.11, and then it works for me
Authentication in mongoose using SCRAM-SHA-1
I faced the same issue while I try to import data from the locale to server.
Those 2 parameters can be important, it worked after I put them:
--authenticationMechanism 'MONGODB-CR'
--authenticationDatabase "admin"
Be careful about the auth mechanism, can be a different one. Check this part of documentation: https://docs.mongodb.com/manual/reference/program/mongoimport/#cmdoption-mongoimport-authenticationmechanism
Had this error myself, turns out I did two things incorrectly (thanks Idos):
Used the mongolab.com username instead of the database one.
Tried to connect to a mongo 3.4 database using a 2.6 shell provided through Ubuntu's repositories. mongo --version to check.
Follow the instructions from this MongoDB page to add their keys and repositories to your APT sources in order to upgrade and keep your MongoDB installation updated going forward.
i had a similar error in that case. put authSourse=admin and ssl=true to your connection
e.g
mongodb://username:password#ds061474.mongolab.com:61474/apitest?authSourse=admin&ssl=true

In nodejs with MySQL

I am Using Nodejs with MySQL.
But problem is that My MYSQL Connection Password Able to see in browser, With this any user get my my SQL username and Password.
Is it possible no one can see my MySQL Connection permanent as its is a server side.
Can any one help me in this.
Do not send you password to client but store it in a variable inside your server-side script. On a request, use it to access database and send only the result of the operation.
If you show your code you might get a more detailed answer then this...
var connection = mysql.createConnection({
host : 'host',
user : 'dbuser',
password : "pword",
database : 'database',
});
connection.connect();
connection.query(etc etc etc)
for full example see mysql module in node.js not works in my case
or another way is to save the configuration and password details in either an env file or other file (or even sqlite db file and load it on startup/restart of your script

Resources