mysql - nodeJS 应用程序无法连接到 google MySQL 数据实例

标签 mysql node.js google-app-engine google-cloud-platform google-cloud-console

我在 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/

相关文章:

python - 我可以将单个 Python 文件部署(更新)到现有的 Google App Engine 应用程序吗?

mysql - 单表动态返回多个平均值的SQL语句是什么

C# 动态 Linq : Strings are assumed to be integers?

javascript - 编写 javascript 库时结合使用 CoffeeScript 和 Node.js 的最佳方法是什么?

node.js - 在node js中获取mongodb集合数据到csv

node.js - gcloud 部署问题 - boot2docker 1.3.1

google-app-engine - Google API 资源管理器重定向到 https ://apis-explorer. appspot.com/apis-explorer/#p/

mysql - 对 sql 列进行排名

mysql - 如何统计Mysql中数据的来源

node.js - Bluebird.js 使用请求时出现未处理的拒绝错误