node.js - 无法使用 Sequelize 连接到 GCP Postgres 数据库

标签 node.js google-cloud-platform sequelize.js

我在 GCP 中创建了一个数据库,但是当我尝试将它与本地主机上的 Node.js 服务器连接时,出现以下错误:

    original: Error: connect ETIMEDOUT 35.202.153.108:5432
      at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
    errno: -4039,
    code: 'ETIMEDOUT',
    syscall: 'connect',
    address: '35.202.153.108',
    port: 5432
  }
这是我在 db.js 中的代码:
const { Sequelize } = require('sequelize');
const sequelize = new Sequelize(
  process.env.DATABASE_NAME,
  process.env.DATABASE_USERNAME,
  process.env.DATABASE_PASSWORD,
  {
    host: process.env.DATABASE_HOST,//35.202.153.108
    dialect: 'postgres',
  }
);

module.exports = sequelize;


db.authenticate()
  .then((t) => console.log('Connection has been established successfully.'))
  .catch((error) => console.error('Unable to connect to the database:', error));
有人可以帮助我连接到 GCP 数据库吗?

最佳答案

试试这个:
Create a TCP connection by using Node.js

const createTcpPool = config => {
  // Extract host and port from socket address
  const dbSocketAddr = process.env.DB_HOST.split(':'); // e.g. '127.0.0.1:5432'

  // Establish a connection to the database
  return Knex({
    client: 'pg',
    connection: {
      user: process.env.DB_USER, // e.g. 'my-user'
      password: process.env.DB_PASS, // e.g. 'my-user-password'
      database: process.env.DB_NAME, // e.g. 'my-database'
      host: dbSocketAddr[0], // e.g. '127.0.0.1'
      port: dbSocketAddr[1], // e.g. '5432'
    },
    // ... Specify additional properties here.
    ...config,
  });
};
该链接还包含其他几个 TCP、Socket、SQL 示例,甚至如何使用 node.js、php 和其他一些示例在 Google Cloud 中为 Postgres 重试连接到 Cloud SQL。

关于node.js - 无法使用 Sequelize 连接到 GCP Postgres 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67126425/

相关文章:

jquery - HTTP 补丁 XmlHttpRequest 支持

javascript - 在新选项卡中渲染静态内容(express、ejs)

ubuntu - 在 Google Cloud VM 中找不到 Conda 命令

group-by - 按结果对分组进行 Sequelize 未定义

mysql - docker 拒绝 postgres 和 mysql 挂载

css - 在 azure Node js Web 应用程序上找不到字体 .woff 404

node.js - 使用 ReactJS 上传文件时 Multer 返回 `undefined`

python - Firestore 数据库写入的性能?

python - 在 google-cloud 上安装 pip 时出错

javascript - 无法访问 node js 中 express.session 的登录值