在使用 Node.js 的情况下创建使用 SSL 证书的 TCP 连接
bookmark_borderbookmark
使用集合让一切井井有条
根据您的偏好保存内容并对其进行分类。
使用具有 SSL(安全套接字层)证书的 Node.js npm mysql 模块,打开与 Cloud SQL for MySQL 的 TCP 连接。
代码示例
如需向 Cloud SQL for MySQL 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
如未另行说明,那么本页面中的内容已根据知识共享署名 4.0 许可获得了许可,并且代码示例已根据 Apache 2.0 许可获得了许可。有关详情,请参阅 Google 开发者网站政策。Java 是 Oracle 和/或其关联公司的注册商标。
[[["易于理解","easyToUnderstand","thumb-up"],["解决了我的问题","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["很难理解","hardToUnderstand","thumb-down"],["信息或示例代码不正确","incorrectInformationOrSampleCode","thumb-down"],["没有我需要的信息/示例","missingTheInformationSamplesINeed","thumb-down"],["翻译问题","translationIssue","thumb-down"],["其他","otherDown","thumb-down"]],[],[],[],null,["# Create a TCP connection with SSL certificates when using Node.js\n\nOpen a TCP connection to Cloud SQL for MySQL by using the Node.js npm mysql module with SSL (Secure Sockets Layer) certificates.\n\nCode sample\n-----------\n\n### Node.js\n\n\nTo authenticate to Cloud SQL for MySQL, set up Application Default Credentials.\nFor more information, see\n\n[Set up authentication for a local development environment](/docs/authentication/set-up-adc-local-dev-environment).\n\n const mysql = require('promise-mysql');\n const fs = require('fs');\n\n // createTcpPool initializes a TCP connection pool for a Cloud SQL\n // instance of MySQL.\n const createTcpPool = async config =\u003e {\n // Note: Saving credentials in environment variables is convenient, but not\n // secure - consider a more secure solution such as\n // Cloud Secret Manager (https://cloud.google.com/secret-manager) to help\n // keep secrets safe.\n const dbConfig = {\n host: process.env.INSTANCE_HOST, // e.g. '127.0.0.1'\n port: process.env.DB_PORT, // e.g. '3306'\n user: process.env.DB_USER, // e.g. 'my-db-user'\n password: process.env.DB_PASS, // e.g. 'my-db-password'\n database: process.env.DB_NAME, // e.g. 'my-database'\n // ... Specify additional properties here.\n ...config,\n };\n\n // (OPTIONAL) Configure SSL certificates\n // For deployments that connect directly to a Cloud SQL instance without\n // using the Cloud SQL Proxy, configuring SSL certificates will ensure the\n // connection is encrypted.\n if (process.env.DB_ROOT_CERT) {\n dbConfig.ssl = {\n sslmode: 'verify-full',\n ca: fs.readFileSync(process.env.DB_ROOT_CERT), // e.g., '/path/to/my/server-ca.pem'\n key: fs.readFileSync(process.env.DB_KEY), // e.g. '/path/to/my/client-key.pem'\n cert: fs.readFileSync(process.env.DB_CERT), // e.g. '/path/to/my/client-cert.pem'\n };\n }\n\n // Establish a connection to the database.\n return mysql.createPool(dbConfig);\n };\n\nWhat's next\n-----------\n\n\nTo search and filter code samples for other Google Cloud products, see the\n[Google Cloud sample browser](/docs/samples?product=cloud_sql_mysql)."]]