简体   繁体   中英

ER_ACCESS_DENIED_ERROR: When i try to connect to the database on remote server - Node.js

I have issue when i try to connect to the database on remote server.

My code:

const mysql = require('mysql');
const database = mysql.createPool({
    host: 'localhost',
    user: 'user',
    password: 'pass',
    database: 'db'
});

database.getConnection(function (err, connection) {
    if (!err) {
        console.log('Database is connected ...');
    } else {
        console.log('Error connecting database ...');
    }
});

The credentials for connection in code is faked. With the right credentials I have, I login successfully on phpMyAdmin on remote server, on datebase that I want to connect. Credentials is good.

When I run script, return this error: view error

Also, when I input credentials for connection with my local database, everything work perfect.

As pointed out by Luuk, you need to replace the localhost with the actual IP address of the remote database server and the port on which the database server is running.

For example -

const database = mysql.createPool({
    host: '123.234.121.234',
    port : '3306',
    user: 'user',
    password: 'pass',
    database: 'db'
}); 

Also, make sure the port is whitelisted and can be accessed over the network. Heres a tiny little diagram for explanation.

在此处输入图片说明

phpmyadmin runs on the same machine as your MySQL server, so it can connect to the server using the generic host name localhost .

I guess, from your question, that your nodejs program runs on some other machine (your personal machine, maybe?). That takes some special-purpose setup to do.

  1. You must use the server's actual hostname in your host: property, not localhost .

  2. MySQL login credentials aren't just username/password. They are host/username/password. You may need to create a new set of credentials for remote access so your nodejs program can get in. Read this: https://webmasters.stackexchange.com/questions/2242/how-to-create-separate-users-in-phpmyadmin-each-one-cant-see-others-databases

  3. If your MySQL server runs on a rented server at some cloud or hosting service, you may need to open up a firewall to allow your machine to connect. If you're on a hosting service, ask their customer support krewe about that. On a cloud service, you want to open port 3306. Look up how to do that in their documentation. (It may be a gnarly configuration task).

Your easiest way of troubleshooting this is to use some MyQSL client program (like MySQL Workbench or HeidiSQL) on your own machine. when you get that to connect, you can use the same credentials in your createPool() call.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM