我在 Google 控制台的付费帐户下托管了一个 NodeJS 应用程序。当我尝试将我的nodeJS应用程序连接到本地主机服务器中的MySQL数据库时,它正在工作,但是一旦我将其配置为在谷歌云控制台中工作,它就会说无法连接到数据库。我成功创建了一个 google SQL 实例,并且确定了用户名和密码,因为我可以通过云控制台连接到数据库。 我在网上引用了很多教程,但没有找到方法......
var con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '1234',
database: 'test'
});
con.connect(function(error){
if(error){
console.log('error');
}
else{
console.log('connected');
}
});
最佳答案
由于此问题带有 google-app-engine
标签,我假设它是您用来部署应用程序的产品。在这种情况下:
App Engine 使用 Unix 套接字连接到 Cloud SQL 实例,因此您需要传递实例的连接名称,如下例所示:
var con = mysql.createConnection({
host: "localhost",
socketPath: "/cloudsql/<PROJECT_ID>:<REGION>:<SQL_INSTANCE_NAME>",
user: "root",
password: "secret"
});
con.connect(function(err) {
if (err) throw err;
console.log("Connected!");
});
您实际上可以通过在本地运行 cloud_sql_proxy 并通过 unix 套接字连接来测试这一点。 Using Cloud SQL for MySQL教程解释了如何做到这一点。
编辑:
如果您使用 App Engine Flex,在 app.yaml 上设置正确的 beta_settings 也很重要,如下例所示:
beta_settings:
# The connection name of your instance, available by using
# 'gcloud beta sql instances describe [INSTANCE_NAME]' or from
# the Instance details page in the Google Cloud Platform Console.
cloud_sql_instances: YOUR_INSTANCE_CONNECTION_NAME
关于mysql - nodeJS 应用程序无法连接到 google MySQL 数据实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57954004/